• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Type safety: Unchecked cast from Object to TreeMap<String,String>

 
Ziyang Zhang
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Above is a simple piece of code. If you put this in Eclipse (or other IDEs), a warning will be shown: Type safety: Unchecked cast from Object to TreeMap<String,String>.
I can add @SuppressWarnings("unchecked") to remove this warning, which I do not want to do.
1. Is there any other ways (industry standard or best practice) to get rid of this warning?
2. Why I get this warning? What is the protential risk in this snippet?
Thank you very much!
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

change returnTreeMap return type to TreeMap<String,String> from Object .

<edit>I do suggest you to use Interface to Type assignment instead of class itself</edit>
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ziyang Zhang wrote:1. Is there any other ways (industry standard or best practice) to get rid of this warning?

No. Well, except by returning Map<String,String>, SortedMap<String,String>, NavigableMap<String,String> or TreeMap<String,String>. In other words, TreeMap itself or one of the interfaces it implements, including the generic types.

2. Why I get this warning? What is the protential risk in this snippet?

Because of type erasure, the JVM cannot check if the object really is a TreeMap<String,String>. It can check if it's a TreeMap, but not the <String,String> part. That means that this cast may succeed, and you'll get casting problems elsewhere, and it will be very difficult to find out what went wrong -- since the cause can be located several classes and minutes away.
 
Ziyang Zhang
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:
Ziyang Zhang wrote:1. Is there any other ways (industry standard or best practice) to get rid of this warning?

No. Well, except by returning Map<String,String>, SortedMap<String,String>, NavigableMap<String,String> or TreeMap<String,String>. In other words, TreeMap itself or one of the interfaces it implements, including the generic types.

2. Why I get this warning? What is the protential risk in this snippet?

Because of type erasure, the JVM cannot check if the object really is a TreeMap<String,String>. It can check if it's a TreeMap, but not the <String,String> part. That means that this cast may succeed, and you'll get casting problems elsewhere, and it will be very difficult to find out what went wrong -- since the cause can be located several classes and minutes away.


Got it! Thank you for your great answer!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic