I have;
List stringList = new ArrayList();
List integerList = new ArrayList();
Is
Expanding on Steve K's answer:
/**
* Performs a forced cast.
* Returns null if the collection type does not match the items in the list.
* @param data The list to cast.
* @param listType The type of list to cast to.
*/
static List super T> castListSafe(List> data, Class listType){
List retval = null;
//This test could be skipped if you trust the callers, but it wouldn't be safe then.
if(data!=null && !data.isEmpty() && listType.isInstance(data.iterator().next().getClass())) {
@SuppressWarnings("unchecked")//It's OK, we know List contains the expected type.
List foo = (List)data;
return retval;
}
return retval;
}
Usage:
protected WhateverClass add(List> data) {//For fluant useage
if(data==null) || data.isEmpty(){
throw new IllegalArgumentException("add() " + data==null?"null":"empty"
+ " collection");
}
Class> colType = data.iterator().next().getClass();//Something
aMethod(castListSafe(data, colType));
}
aMethod(List foo){
for(Foo foo: List){
System.out.println(Foo);
}
}
aMethod(List bar){
for(Bar bar: List){
System.out.println(Bar);
}
}