I am testing some small practicals with JAVA generics concept.
I try to return a List from a function that is generic but compile does not allow me to do so.
Check the code below :
package com.test.generic.method;
import java.util.ArrayList;
import java.util.List;
public class Sample_3<T> {
public <T> List<T> testReturn(T t) {
List<T> list = new ArrayList<T> ();
list.add(t);
return list;
}
public static void main(String a[]) {
String s = "Gunjan";
Sample_3 sample = new Sample_3<String>();
List<String> list =(List<String>) sample.testReturn(sample);
for(String ab : list){
System.out.println(ab);
}
}
}
It gives
ClassCastException.
How can I return the list from the generic function ?
And why JAVA has added such compile time feature ?
Thanks,
Gunjan.
Thepurpose of the generics is to allow you freedom to specify. So you can do something like:which would then allow you to do e.g.
The issue with your code is that the intent of your method isn’t really generic – the method is written to return a List<String>. The
<T>in your code doesn’t actually affect anything.In response to your further question –
You’ve written the following:
Your generic parameter T sets the type that can vary. YOu can do it onthe method level, as above, or on the class level as well:
e.g.