0
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

Pritpal
  • 571
  • 1
  • 6
  • 11
  • 3
    You declare `ChooserVer2 chooser` without specifying the generic type parameter. See [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – khelwood Jul 21 '20 at 15:39
  • Your `chooser` variable is of a *raw type*. If you change the type to `ChooserVer2` it will be fine. – Jon Skeet Jul 21 '20 at 15:39

1 Answers1

0

The ChooserVer2 uses no generic type, although declared - this is called a raw parameter. As long as it is wanted the object to use a generic type and return an instance of it through the T randomObj() method, it's needed to declare it so:

ChooserVer2<Integer> chooser = new ChooserVer2<>(intList);
Integer i = chooser.randomObj();
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183