public class ChooserVer2<T> {
private final T[] choice;
public ChooserVer2(Collection<T> collection) {
choice = (T[])collection.toArray();
}
public T randomObj() {
Random rnd = ThreadLocalRandom.current();
return choice[rnd.nextInt(choice.length)];
}
public static void main(String[] args) {
List<Integer> intList = Arrays.asList(5, 10, 15);
ChooserVer2 chooser = new ChooserVer2(intList);
Integer i = chooser.randomObj();
}
}
The line Integer i = chooser.randomObj();
complains that a cast is required to Integer since the return type is Object.
This has me confused since my understanding is that generics have type information at compile time and we already know that randomObj return type is of Type T, which in this case happens to be an Integer.
Why is the compiler complaining of a cast then ?
UPDATE : At line (T[])collection.toArray()
, the compiler is showing a warning about an unchecked cast. I've been reading about this on effective java book and it says that the compiler cant vouch for the safety of the cast at runtime because the program wont know what type T represents. Can someone please explain this in a more intuitive way ?
Thanks