• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about the use of TreeMap

 
Zach Burnham
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
General question about TreeMap:

I have a use for what I'd call an "associative array" in Perl, and it's my understanding that TreeMap will fill that need and sort the keys at the same time, a bonus.

However, with the code I've written, I keep getting a warning about an unchecked or unsafe operation, like thus:


When I do that, I get this:

I've googled the error but the most definitive thing I've seen is "ignore the warning." That seems kinda pants to me. Any ideas how I can do this correctly?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With Java 5 we got "generics" which among other things lets us specify what we're going to put into a collection. To avoid the warnings you'll need syntax like:

Map<String, MyClass> = new TreeMap<String, MyClass>();

Now the compiler can enforce String keys and MyClass objects. If you try to put anything else in you'll get compile time errors. And you won't have to cast MyClass objects when you take them out. It's pretty slick.

I have only scratched the surface on Generics myself with minimal syntax to avoid warnings and enforce some basic rules. There is much more to it. Google for "Java generics tutorial" or "faq" and see what's out there. Some of the better experts will likely chime in with their favorite resources for learning more.

BTW: Here's a cheat sheet for collections. See if TreeMap - with ordered keys - is really what you need.
 
Zach Burnham
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:

BTW: Here's a cheat sheet for collections. See if TreeMap - with ordered keys - is really what you need.[/QB]


It is, for reasons that probably have more to do with ugly code than actual utility. Thanks.
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right but it you do not have to worry about casting when get the objects out of your tree, which is a good thing. Also avoids nasty ClassCastExceptions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic