I'm taking SCJP 5.0 shortly. But really scared of generics and File IO stuff
I was playing with generics and i'm unable to understand why the following works:
Can someone explain why the statement in main method works?
I thought when we create a reference of type 'Test<String>', then all occurrences of 'T' should be replaced by 'String'. But looks like that's not the way it works. There is no constructor that takes Integer and we are creating a reference of type 'Test<String>'. I'm totally confused
[ October 25, 2008: Message edited by: Aravind Jerubandi ] [ October 25, 2008: Message edited by: Aravind Jerubandi ]
-Aravind<br />SCJP 5.0 (91%), Preparing for SCBCD.
Joined: Dec 17, 2006
Actually i was comparing the above code with the below one:
Look at this version of your programAll I have done is print out the type of "g". You will see that it is no longer type-safe and, although it compiles, there is a warning. I trust you are familiar with the Java� Tutorial?
Joined: Dec 17, 2006
I've studied generics, and i know that the type safe are removed through type erasure during compilation. But the way i used to interpret the code was; whenever there is a class type is defined, i used to replace all the occurrences of generic type with the class type. for ex, in the above code:
Test<String> t = new Test(new Integer(1));
As Test class is defined with a generic parameter type 'Test<t>' and in the above line, the reference is defined as 'Test<String>', in my mind, i used to replace all the occurrences of 'T' with 'String' to check for compiler errors. I'm confused here, because the constructor is defined as 'Test(T g)' and in the above code we are passing Integer in the constructor and the parameter type is String.
I know my stupid brain is missing something here and i'm hopelessly confused. Can some one please clarify this with good example.
yes long you are right. Once you have assigned an untyped arrayList to a typed one, then all the code after that will use the type of the arrayList. But the code is not necessarily type safe because you have used legacy code. Doing the opposite of your code will lead to a ClassCastException