Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics with HashSet

 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! Why this code compiles without errors and runs without exceptions:



Output:
[sdlkfj, test6.Animal@1f9dc36]

I expected sst can contain only integers.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy ranchers!

What an object can do and can't do does not depend only on the objects type, but also on the compile type of the variable.

Your variable sst is defined as a non-generic Set. Therefore it can take any object, strings as well.

It is like in
Object o = new String("hi");

You can do only object-things to o. Not string-things.
But you can assign different obects of any class to o:
o = new Integer(3);

Likewise you can assign differnet sets to your variable, e.g. try:
sst = new TreeSet<Thread>();
sst.add(new Integer(8));




Yours,
Bu.
 
Brian Cole
Author
Ranch Hand
Posts: 907
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Andry Dub:
I expected sst can contain only integers.


Java generics are implemented with Type Erasure, which means that the types of objects added to sst aren't checked at runtime.

If you change your code slightly, though, you will get errors at compile time:

Set<Integer> sst = new HashSet<Integer>();
sst.add(new String("sdlkfj")); // won't compile
sst.add(new Animal()); // won't compile
System.out.println(sst);
 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for valuable information!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic