Tuesday, December 3, 2013

Convert List Generic ke list tipe tertentu di java

Berikut ini adalah contoh bagaimana mengconvert list generic ke list tipe tertentu di java

package fjr.test;
import java.util.ArrayList;
/**
*
* @author fajar
*/
public class ConvertGeneric{
public static void main(String[] args){
ArrayList list = getSampleList();
print(list);
}
static public <T>ArrayList<T> getSampleList(){
ArrayList<String> m = new ArrayList(){{
add("A"); add("B"); add("C");
}};
return (ArrayList<T>)m;// dicasting di sini....
}
static <T>void print(ArrayList<T> list){
for(int i =0; i< list.size(); i++){
System.out.println(list.get(i));
}
}
}
// output
//A
//B
//C