spiffy.core.util
Class CollectionHelper

java.lang.Object
  extended by spiffy.core.util.CollectionHelper

public class CollectionHelper
extends Object

Helper methods for collections

Author:
Kasper B. Graversen, (c) 2007

Constructor Summary
CollectionHelper()
           
 
Method Summary
static
<T> ArrayList<T>
arrayList(T... elements)
          An easy way to construct an array list. just do ArrayList<String> al = CollectionHelper.ArrayList("a", "b", "c"); Rather than ArrayList<String> al = new ArrayList<String>() al.add("a"); al.add("b"); al.add("c");
static ArrayList<? super Object> arrayListObjects(Object... elements)
          An easy way to generate an ArrayList holding mixed types of objects.
static
<T> T
firstOnly(Collection<T> collection)
          Checks to see if the collection is of size 1 and if so returns that element.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

CollectionHelper

public CollectionHelper()
Method Detail

arrayList

public static <T> ArrayList<T> arrayList(T... elements)
An easy way to construct an array list. just do
 ArrayList<String> al = CollectionHelper.ArrayList("a", "b", "c");
 
Rather than
 ArrayList<String> al = new ArrayList<String>()
 al.add("a");
 al.add("b");
 al.add("c");
 

Parameters:
elements - the elements to create an ArrayList of
Returns:
a freshly created ArrayList containing elements given as arguments. If elements is null, null is returned.
Since:
0.1

arrayListObjects

public static ArrayList<? super Object> arrayListObjects(Object... elements)
An easy way to generate an ArrayList holding mixed types of objects. The current type system in Java does not allow you to say
 ArrayList<? extends Object> genericList = arrayList(1, "two", 3.0);
 
thus you should use this helper method instead

Parameters:
elements - elements to store in the list
Returns:
an array list

firstOnly

public static <T> T firstOnly(Collection<T> collection)
Checks to see if the collection is of size 1 and if so returns that element.

This method is particularly nice for DAO implementations, as all get methods should return a collection of objects rather than just one object. This enables the DAO to return several objects in case the query is wrong, or worse, if there are data problems in the database. Hence avoid code such as

 class PersonDao {
        Person getPerson(String arg1, String arg2);
 }
 
instead use
 class PersonDao {
        Collection<Person> getPerson(String arg1, String arg2);
 }
 
and query the first element with this method

Parameters:
collection - any non-collection
Returns:
first element of a collection, if the collection has a size of 1.
Throws:
IllegalStateException - when collection is not of size 1
Since:
0.3