public class GenericDemo<T> {
T data[] = (T[])new Object[1];
public static void main(String[] args) {
GenericDemo<String> gdStr = new GenericDemo<>();
gdStr.data[0] = new String("Hello"); //Runtime Class cast exception
GenericData<Integer> dataInt = new GenericData<>();
dataInt.setObj(new Integer(25));
System.out.println(dataInt.getObj());
GenericData<String> dataString = new GenericData<>();
dataString.setObj("Hello World");
System.out.println(dataString.getObj());
}
}
class GenericData<T> {
private T obj;
public void setObj(T obj) {
this.obj = obj;
}
public T getObj(){
return obj;
}
}
In the above code runtime error --> gdStr.data[0] = new String("Hello"); but compiles just fine. the same runs fine when value is set and called in getter/setter. May I know the problem here.