This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Generic Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Generic Collections" Watch "Generic Collections" New topic
Author

Generic Collections

Martin Allison
Greenhorn

Joined: Feb 28, 2009
Posts: 1
Hi

What is the difference between

Set<myClass> s1 = new TreeSet<myClass>();
and
Set<myClass> s2 = new TreeSet();

s2 seems to have the same restricions as s1, so why is there a warning on s2?

Marty
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16817
    
  19


For backward compatability, you are allowed to declare references to classes with generics, and instantiate classes with generics, without specifying the generic type.... However, it will generate a warning error.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19232

Consider the following code:

The above code will throw a ClassCastException when iterating over stringSet, because it will cast the Integer object to a String.

By warning you the compiler tells you that the code may cause problems at some stage. Therefore, in an ideal situation, you make sure there are no warnings. Sometimes you can't however; in those cases it is vital that you document why the warning is safe to ignore. If you can't then it isn't safe and you should prevent the warning.

An example of a warning you may ignore:


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Generic Collections
 
Similar Threads
== and equals question required
equals() method
Flagging duplicate lines when comparing the input from two seperate text files
Treeset throwing ClassCastException
Generic