File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics with HashSet" Watch "Generics with HashSet" New topic

Generics with HashSet

Andry Dub
Ranch Hand

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

[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));


all events occur in real time
Brian Cole
Ranch Hand

Joined: Sep 20, 2005
Posts: 878
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

bitguru blog
Andry Dub
Ranch Hand

Joined: Nov 06, 2007
Posts: 43
Thank you for valuable information!
I agree. Here's the link:
subject: Generics with HashSet
It's not a secret anymore!