| Author |
Doubt in generics..please help..
|
Manpreet Kaur
Greenhorn
Joined: Jul 03, 2008
Posts: 8
|
|
The following question is from javabeat.net public class Gen<G> { G g; Gen(G g) { this.g =g; } public static void main(String[] args) { Gen<String> arr[] = new Gen[5]; //line 1 arr[0] = new Gen("Java"); //line 2 arr[1] = new Gen(1); //line 3 arr[2] = (Gen<String> new Gen(1); //line 4 arr[3] = (Gen<String> new Gen<Integer>(1); //line 5 for(Gen o:arr) { System.out.println(o); } } } The options are a)Compile time Error at line 1 b)Compile time Error at line 3 c)Compile time Error at line 4 d)Compile time Error at line 5 e)Run Time Error Answer 3) d. We can cast raw type to specific type but we cannot type cast Integer type to String type My question is why does not compiler give an error on line 3 when we are trying to add and int value to a type-safe String. Please help. Thanks [ July 09, 2008: Message edited by: Manpreet Kaur ] [ July 09, 2008: Message edited by: Manpreet Kaur ]
|
 |
Raphael Rabadan
Ranch Hand
Joined: Jul 05, 2008
Posts: 141
|
|
Hello, on line 3 you will only have a warning of safety because you arent using any parameter to the raw type. So, it should give an error if it was like since its not, will just pass.
|
SCJP Java 6 (98%) - Story, SCJA (88%) - Story
|
 |
Soroj Margun
Ranch Hand
Joined: Jun 15, 2008
Posts: 44
|
|
Hi Manpreet, You're already answer yourseft.
We can cast raw type to specific type
Object is still raw type unless you explicit specify it to be a generic type. On the other hand, all generic type is also put raw type. Do not forget this for your SCJP.
|
SCJP 1.2; SCWCD 1.2,1.4; SCBCD 1.3; SCJD 5.0
|
 |
Nabila Mohammad
Ranch Hand
Joined: Nov 05, 2007
Posts: 661
|
|
|
Can some one please elaborate on what's the "RAw type"?
|
The future belongs to those who believe in the beauty of their dreams.Dream BIG!
|
 |
 |
|
|
subject: Doubt in generics..please help..
|
|
|