• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic Collections

 
Martin Allison
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 20881
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic