0

I am learning Java Generics these days. Right now,I am going through "Type Eraser" concept. I have put together a small java program based on this. Here is my complete code:

/*
* Bridge method demonstration
*/
class Node<T>{
  public T data;

  public Node(T data){
   this.data = data;
  }

  public void setData(T data){
   System.out.println("Node.setData");
   this.data = data;
  }
}

class MyNode extends Node<Integer>{
 public MyNode(Integer data){ super(data); }

 public void setData(Integer data){
  System.out.println("MyNode.setData");
  super.setData(data);
 }
}

Now,the following code throws ClassCastException:

// Bridge method demo
  System.out.println("Demonstrating bridge method:");
  MyNode mn = new MyNode(5);
  Node n = mn;
  n.setData("Hello");
  Integer x = mn.data;

Error:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer                                                             
        at MyNode.setData(genericfirst.java:96)                                                                                                                           
        at genericfirst.main(genericfirst.java:177)

Can somebody help me understand what exactly is causing the problem. Since I am unable to guess what's happening,I think I have not understood the concept of bridge method properly. It would be helpful if someone can explain a little bit about bridge methods too.

n00b
  • 214
  • 1
  • 12
  • 1
    You are not type casting your string to store in integer object see this for more information.http://stackoverflow.com/questions/5585779/how-to-convert-string-to-int-in-java – smali Oct 31 '14 at 08:53
  • 1
    The problem is that you've chosen to ignore all the compiler warnings about generics, and ended up with broken code. Try changing `Node n = mn;` to the correct `Node n = mn;` and then you'll get a proper compile *error* at `n.setData("Hello");` because you're calling a method that only accepts an Integer, with an argument that's of type String. – Erwin Bolwidt Oct 31 '14 at 08:57

1 Answers1

2

You are trying to put a String value in an Integer, that's why you got this exception.

Try using parseInt() like this:

 Integer x = Integer.parseInt(mn.data);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78