Skip to content

Instantly share code, notes, and snippets.

@jesperronn
Last active December 14, 2015 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesperronn/5056355 to your computer and use it in GitHub Desktop.
Save jesperronn/5056355 to your computer and use it in GitHub Desktop.
Java Generic collection objects, where you can dot them
package com.my.collections;
import java.io.Serializable;
import java.util.*;
/**
* <p/>
* Superclass for handling a collection of objects. He super class contains
* the basic collection along with a few generic methods
* <p/>
* Methods:
* .size()
* .isEmpty()
* .addAll(Collection<T>)
* .getFirst()
*
* Methods for easy retrieval of object (very useful during refactoring):
* .asList()
* .asSet()
* .getCollection()
*
* WARNING: The underlying collection is UNSORTED for now
* Ideally, we should change inside this class, but at the risk of breaking other subclasses
*
*/
public class GenericCollection<T> implements Serializable {
private static final long serialVersionUID = -1L;
protected Collection<T> collection;
public GenericCollection() {
this(new HashSet<T>());
}
public GenericCollection(Collection<T> collection) {
if (collection == null || collection.isEmpty()) {
collection = new HashSet<T>();
}
this.collection = collection;
}
/**
* initialize this collection with all items input from constructor
* @param items any number of items that should go into the collection
*/
public GenericCollection(T... items) {
this(Arrays.asList(items));
}
/**
* @return size of collection
*/
public int size() {
return collection.size();
}
/**
* @return true if no elements found in collection (or collection uninitialized)
*/
public boolean isEmpty() {
return collection == null || collection.isEmpty();
}
/**
* @return the collection of value objects
*/
public Collection<T> getCollection() {
return collection;
}
public boolean add(T item) {
return collection.add(item);
}
public void addAll(Collection<T> objects) {
collection.addAll(objects);
}
/**
* get first item in collection or null
*
* @return first item in collection or null
*/
public T getFirst() {
if (collection.size() > 0) {
return collection.iterator().next();
}
return null;
}
public Set<T> asSet() {
return new HashSet<T>(collection);
}
public List<T> asList(){
return new ArrayList<T>(collection);
}
/**
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this method returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this collection
*/
// @Override
public void clear() {
collection.clear();
}
@Override
public String toString() {
return ClassUtils.getClassName(this) + ":{" + collection + '}';
}
}
package com.my.collections;
import java.util.*;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.internal.matchers.StringContains.containsString;
/**
* tests the basic functionality and constructors
*/
public class GenericCollectionTest {
GenericCollection<String> collection, undefinedCollection, emptyCollection;
@Before
public void setUp() {
collection = new GenericCollection<String>(newHashSet("b", "a", "d", "c"));
emptyCollection = new GenericCollection<String>();
}
@Test
public void testConstructorNoParams() {
assertThat("precondition...collection is null", undefinedCollection, nullValue());
undefinedCollection = new GenericCollection<String>();
assertThat("collection is defined", undefinedCollection, notNullValue());
assertThat("is empty no size", undefinedCollection.size(), is(0));
assertThat("is empty ", undefinedCollection.isEmpty(), is(true));
assertThat("can add to undefined collection", undefinedCollection.add("h"), Matchers.is(true));
}
@Test
public void testConstructorArray() {
assertThat("precondition...collection is null", undefinedCollection, nullValue());
undefinedCollection = new GenericCollection<String>(Arrays.asList("b", "a", "d", "c"));
assertThat("collection is defined", undefinedCollection, notNullValue());
assertThat("is empty no size", undefinedCollection.size(), is(4));
}
@Test
public void testConstructorSet() {
assertThat("precondition...collection is null", undefinedCollection, nullValue());
undefinedCollection = new GenericCollection<String>(newHashSet("b", "a", "d", "c"));
assertThat("collection is defined", undefinedCollection, notNullValue());
assertThat("is empty no size", undefinedCollection.size(), is(4));
}
@Test
public void testConstructorMultipleItems() {
assertThat("precondition...collection is null", undefinedCollection, nullValue());
undefinedCollection = new GenericCollection<String>("b", "a", "d", "c");
assertThat("collection is defined", undefinedCollection, notNullValue());
assertThat("is empty no size", undefinedCollection.size(), is(4));
}
@Test
public void testSize() {
assertThat("size for collection is 4", collection.size(), is(4));
assertThat("size for empty collection ", emptyCollection.size(), is(0));
}
@Test
public void testIsEmpty() {
assertThat("collection is not empty", collection.isEmpty(), is(false));
assertThat("emptyCollection is empty", emptyCollection.isEmpty(), is(true));
}
@Test
public void testGetCollection() {
Collection<String> result = collection.getCollection();
assertThat("returned is a collection", result instanceof Collection, is(true));
assertThat("returned is a Set", result instanceof Set, is(true));
assertThat("returned is not a List", result instanceof List, is(false));
}
@Test
public void testAdd() {
assertThat("precondition: size is 4", collection.size(), is(4));
collection.add("S");
assertThat("added item is also counted", collection.size(), is(5));
//assertThat("collection items contain new value 'S'", collection.toString(), is("GenericCollection:{[b, a, d, c, S]}"));
assertThat("collection items contain new value 'S'", collection.toString(), containsString("S"));
}
@Test
public void testAddMultiple() {
assertThat("precondition: size is 4", collection.size(), is(4));
collection.add("S");
collection.add("S");//adding same again should only add if not exists.
//which is standard Set<T> behaviour
assertThat("added item is also counted", collection.size(), is(5));
//assertThat("collection items contain new value 'S'", collection.toString(), is("GenericCollection:{[b, a, d, c, S]}"));
assertThat("collection items contain new value 'S'", collection.toString(), containsString("S"));
}
@Test
public void testAddAllForCollectionWithContent() {
assertThat("precondition: size is 4", collection.size(), is(4));
collection.addAll(Arrays.asList("S", "T"));
assertThat("added item is also counted", collection.size(), is(6));
//assertThat("collection items contain new value 'S' and 'T'", collection.toString(), is("GenericCollection:{[b, a, d, c, S, T]}"));
assertThat("collection items contain new value 'S'", collection.toString(), containsString("S"));
assertThat("collection items contain new value 'T'", collection.toString(), containsString("T"));
}
@Test
public void testGetFirst() {
assertThat("first item is", collection.getFirst(), equalTo("d"));
}
@Test
public void testGetFirstShouldReturnNullWhenEmpty() {
assertThat("first item is", emptyCollection.getFirst(), nullValue());
}
@Test
public void testAsSet() {
Set<String> result = collection.asSet();
assertThat("set returned", result.size(), is(4));
assertThat("result is a HashSet", result instanceof HashSet, is(true));
}
@Test
public void testAsList() {
List<String> result = collection.asList();
assertThat("list returned", result.size(), is(4));
assertThat("result is a ArrayList", result instanceof ArrayList, is(true));
}
@Test
public void testClear() {
collection.clear();
assertThat("clear collection size", collection.size(), is(0));
assertThat("clear collection is empty", collection.isEmpty(), is(true));
}
private HashSet<String> newHashSet(String... strings) {
HashSet<String> set = new HashSet<String>();
Collections.addAll(set, strings);
return set;
}
}
package com.my.collections;
import java.io.Serializable;
import java.util.*;
/**
* <p/>
* Superclass for handling a collection of objects. He super class contains
* the basic collection along with a few generic methods
* <p/>
* Methods:
* .size()
* .isEmpty()
* .addAll(Collection<T>)
* .getFirst()
*
* Methods for easy retrieval of object (very useful during refactoring):
* .asList()
* .asSet()
* .getCollection()
*
* WARNING: The underlying collection is UNSORTED for now
* Ideally, we should change inside this class, but at the risk of breaking other subclasses
*
*/
public class GenericList<T> implements Serializable {
protected List<T> collection;
public GenericList() {
collection = new ArrayList<T>();
}
public GenericList(List<T> objects) {
collection = new ArrayList<T>();
collection.addAll(objects);
}
/**
* @return size of collection
*/
public int size() {
return collection.size();
}
/**
* @return true if no elements found in collection (or collection uninitialized)
*/
public boolean isEmpty() {
return collection == null || collection.isEmpty();
}
/**
* @return the collection of value objects
*/
public Collection<T> getCollection() {
return collection;
}
public void add(T item) {
collection.add(item);
}
public void addAll(Collection<T> objects) {
collection.addAll(objects);
}
/**
* get numbered item in collection or IndexOutOfBounds
*
* @return numbered item in collection or null
*/
public T get(int pos) {
return collection.get(pos);
}
/**
* get first item in collection or null
*
* @return first item in collection or null
*/
public T getFirst() {
if (collection.size() > 0) {
return collection.get(0);
}
return null;
}
/**
* get last item in collection or null
*
* @return last item in collection or null
*/
public T getLast() {
if (collection.size() > 0) {
return collection.get(collection.size()-1);
}
return null;
}
public Set<T> asSet() {
return new HashSet<T>(collection);
}
public List<T> asList(){
return new ArrayList<T>(collection);
}
/**
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this method returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this collection
*/
// @Override
public void clear() {
collection.clear();
}
@Override
public String toString() {
return "" + this.getClass().getSimpleName() + ":{" + collection + '}';
}
}
package com.my.collections;
import java.util.*;
/**
* <p/>
* Superclass for handling a collection of objects. He super class contains
* the basic collection along with a few generic methods
* <p/>
* Methods:
* .size()
* .isEmpty()
* .addAll(Collection<T>)
* .getFirst()
*
* Methods for easy retrieval of object (very useful during refactoring):
* .asList()
* .asSet()
* .getCollection()
*
* WARNING: The underlying collection is UNSORTED for now
* Ideally, we should change inside this class, but at the risk of breaking other subclasses
*
*/
public abstract class GenericSortedCollection<T> {
//private static final long serialVersionUID = -1L; //comparator is not serializable
protected TreeSet<T> collection;
protected Comparator<T> comparator;
public GenericSortedCollection(Comparator<T> comparator) {
this(new TreeSet<T>(comparator));
this.comparator = comparator;
}
public GenericSortedCollection(TreeSet<T> collection) {
if (collection == null) {
collection = new TreeSet<T>();
}
this.collection = collection;
}
public GenericSortedCollection(Comparator comparator, Collection<T> collection) {
this(comparator);
if(collection == null){
return;
}
for (T item : collection) {
this.collection.add(item);
}
}
/**
* @return size of collection
*/
public int size() {
return collection.size();
}
/**
* @return true if no elements found in collection (or collection uninitialized)
*/
public boolean isEmpty() {
return collection == null || collection.isEmpty();
}
/**
* @return the collection of value objects
*/
public Collection<T> getCollection() {
return collection;
}
public void add(T item) {
collection.add(item);
}
public void addAll(Collection<T> objects) {
collection.addAll(objects);
}
/**
* get first item in collection or null
*
* @return first item in collection or null
*/
public T getFirst() {
if (collection.size() > 0) {
return collection.iterator().next();
}
return null;
}
public Set<T> asSet() {
return new TreeSet<T>(collection);
}
public List<T> asList(){
return new ArrayList<T>(collection);
}
/**
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this method returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this collection
*/
// @Override
public void clear() {
collection.clear();
}
@Override
public String toString() {
return ClassUtils.getClassName(this) + ":{" + collection + '}';
}
}
package com.my.collections;
/**
*
* convenience class to get a sum really easy
*/
public class IntegerCollection extends GenericList<Integer>{
public Integer getSum(){
Integer sum = 0;
for (Integer i : collection) {
sum += i;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment