my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics with HashSet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics with HashSet" Watch "Generics with HashSet" New topic
Author

Generics with HashSet

Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Hi! Why this code compiles without errors and runs without exceptions:



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

I expected sst can contain only integers.


Java is my love
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
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.


all events occur in real time
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
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);


bitguru blog
Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Thank you for valuable information!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Generics with HashSet
 
Similar Threads
Why can't we assign parent class object to child class reference?
constructor doubt
parantheses in explicit casting
Reference Variable Casting
Question about Collections.sort()