File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in generics..please help..

 
Manpreet Kaur
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 141
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Soroj Margun
Ranch Hand
Posts: 44
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nabila Mohammad
Ranch Hand
Posts: 661
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can some one please elaborate on what's the "RAw type"?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic