• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Dought

 
Prasad Tamirisa
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Can any one tell me the difference between these two codes.
I always have a confusion on this.

1)

2)


Please suggest.
 
Louis Moloney
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another difference:

Code 1 compiles, Code 2 doesn't
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sasha Ruehmkorf:
Another difference:

Code 1 compiles, Code 2 doesn't


Strictly yes, but Louis has implicitly corrected that mistake.
 
Joe Irudayaraj
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sasha,
Both of the Statements are getting compiled for me

Regards
Joe
 
Prasad Tamirisa
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For me also,

Both the statements are getting compiled.
 
Saket Barve
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
cannot compile. It needs to be
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic