aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Dought Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics Dought" Watch "Generics Dought" New topic
Author

Generics Dought

Prasad Tamirisa
Ranch Hand

Joined: Mar 26, 2007
Posts: 130
Hi Can any one tell me the difference between these two codes.
I always have a confusion on this.

1)

2)


Please suggest.


Regards,
Durga Prasad
Louis Moloney
Ranch Hand

Joined: Feb 06, 2007
Posts: 59
Set vals = new TreeSet<String>();

this has no effect as far as i can see, you have a set reference that has no type safe protection. The compiler sees (Set vals) and thinks it can put anything in it, which it can. As at runtime the jvm sees TreeSet as at runtime TreeSet<String> does not exist only TreeSet exists on the heap.

Remember this type of type safety is compile only, but you have undone the compile time safety by making the ref like that.

this will give you compile time safety:

Set<String> vals = new TreeSet<String>();

type safey with generics is quite complicated , with the above and using legacy code you can run into problems.


Sasha Ruehmkorf
Ranch Hand

Joined: Mar 29, 2007
Posts: 115
Another difference:

Code 1 compiles, Code 2 doesn't
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Originally posted by Sasha Ruehmkorf:
Another difference:

Code 1 compiles, Code 2 doesn't


Strictly yes, but Louis has implicitly corrected that mistake.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Joe Irudayaraj
Greenhorn

Joined: Aug 03, 2005
Posts: 5
Hi Sasha,
Both of the Statements are getting compiled for me

Regards
Joe
Prasad Tamirisa
Ranch Hand

Joined: Mar 26, 2007
Posts: 130
For me also,

Both the statements are getting compiled.
Saket Barve
Ranch Hand

Joined: Dec 19, 2002
Posts: 229
cannot compile. It needs to be
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics Dought