Forums Register Login

Doubt in generics..please help..

+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Can some one please elaborate on what's the "RAw type"?
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 796 times.
Similar Threads
Questions on Generics
Genric problem
doubt on code
Doubts in Generics: Why dont this throw exception?
javabeat free mock test doubt
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 15:56:10.