my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Question about the use of TreeMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question about the use of TreeMap" Watch "Question about the use of TreeMap" New topic
Author

Question about the use of TreeMap

Zach Burnham
Greenhorn

Joined: Feb 15, 2006
Posts: 16
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Zach Burnham
Greenhorn

Joined: Feb 15, 2006
Posts: 16
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

Joined: Feb 11, 2006
Posts: 288
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.


java j2ee job interview questions with answers | Learn the core concepts and the key areas
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question about the use of TreeMap
 
Similar Threads
eclipse 3.1, java 5
Warning while compiling
warining is coming while using Map why? code here
TreeMap compile error
What is the "standard way" when getting data from a DB?