Probably some java enthusiast can answer this question for me. I was referring to the Collections API to convert a list to array. I was shocked to find that the method was generic.
<T> T[] toArray(T[] a)
I was wondering why the method was declared generic when the type is itself declared with one. So, in order to convince myself, I wrote the following code and a test case. Please excuse if the code looks odd and isn't following any standard; its written quickly for the purpose of this blog.
public class AList<E> {
private final List<E> list;
public AList(List<E> list) {
super();
this.list = list;
}
public boolean add(E value){
return this.list.add(value);
}
public int size(){
return this.list.size();
}
public E[] toArray(E[] a) {
System.arraycopy(list.toArray(), 0, a, 0, size());
return a;
}
}
The first part of the test case is for pre-Java5 collection and the next for the type safe Java 5 way.
@Test
public void testAListToArray() {
AList list = new AList(new ArrayList());
list.add("Not type safe");
String[] sl = (String[]) list.toArray(new String[list.size()]);
assertEquals(sl.length, list.size());
AList<String> list2 = new AList<String>(new ArrayList<String>());
list2.add("Type safe");
String[] s2 = list2.toArray(new String[list.size()]);
assertEquals(s2.length, list2.size());
}
Both worked perfectly fine and the test passed. So, back to square one --> I'm unable to figure out why they method is declared generic with an additional parameterized type.
