0
public class Node<T> {
    private  T     objReference;
    private Node<T> nextReference;

    public Node(Object ref) {
            objReference = (T) ref;
            nextReference =   null;

    }

    public Node() {
        objReference = null ;
        nextReference = null ;
    }

    public void assignNextReference(Node ref) {
        this.nextReference = ref;
    }

    public Node getNextReference() {
        return this.nextReference;
    }

    public T getObjReference() {
        return objReference ;
    }

    public void assignObjReference(Object ref) {
        try {
            objReference = (T) ref;

        } catch(ClassCastException e) {
            System.out.println(e);
        }
    }
}

I expected the following call to throw a ClassCastException but no exception is thrown.

 Node<Integer> n = new Node<Integer>() ;
       
 n.assignObjReference(new String("String"));

When we use Integer for type parameter, assignObjectReference method would try to cast the String reference to the type parameter which is Integer. Since this is not possible, we should be getting a ClassCastException. What am I missing here?

Sushrut Kaul
  • 83
  • 10
  • 2
    Check your compiler warnings. You should have gotten one like, "Note: Node.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details." – John Kugelman Nov 01 '20 at 22:42
  • 2
    Also, if you are using an IDE such as IntelliJ IDEA, or Eclipse, don't ignore highlighted pieces of code. Hover your cursor over them and see what warning you get. Google any warning that you don't understand. And to answer your question, you don't get an exception because the Java compiler applies *type erasure* on generics - look up this term for more details. – k314159 Nov 01 '20 at 22:46
  • I just saw that IntelliJ is reporting the following : "Unchecked cast: java.lang.Object to T". At runtime, shouldn't it fail the cast operation though as the passed object is of type String and you are essentially trying to cast it to Integer? – Sushrut Kaul Nov 01 '20 at 22:49
  • 2
    Does this answer your question? [No ClassCastException is thrown inside Java generics](https://stackoverflow.com/questions/26699731/no-classcastexception-is-thrown-inside-java-generics) – Sztyler Nov 01 '20 at 23:10

0 Answers0