Forums Register Login

HashMap.keySet()

+Pie Number of slices to send: Send
The method HashMap.keySet() returns a set of the keys in the HashMap. Are those keys in any special order, like perhaps arranged in the order of their hash codes or something? Is there some way to control the order of the keys returned by this method?
+Pie Number of slices to send: Send
The first paragraph of the JavaDoc API for HashMap tells all.
+Pie Number of slices to send: Send
 

Originally posted by Kevin Tysen:
Is there some way to control the order of the keys returned by this method?


Use a TreeSet (comparison order) or LinkedHashMap (insertion order) instead of HashMap (unspecified order).
+Pie Number of slices to send: Send
Thank you. My computer only has java 1.3 which does not include LinkedHashMap, so I think I will try TreeSet.

My plan is wrap the keys and mappings together in a class (MyAwesomeClass), and make the class implement Comparable, which means I have to implement the interface, which is int compareTo(MyAwesomeClass mac).
And because the explanation in Comparable recommends that compareTo be consistent with equals, I suppose I should override the equals method too, while I'm at it.
So if MyAwesomeClass is a Comparable, then that guarantees that the "natural ordering" of the elements in the TreeSet will be determined by the compareTo method in MyAweSomeClass.

Is that how to use TreeSet?
+Pie Number of slices to send: Send
That's one way.

Another way is to use your regular non-comparible objects, and use a comparator in the constructor of the TreeSet:

Instead of natural ordering, this will use the comparator for the ordering.
+Pie Number of slices to send: Send
Thank you. There's just one problem with this. TreeSet does not have the methods put and get which are in HashMap. But when I looked at the API, I noticed a class called TreeMap. That seems to be what I need. It has get and put methods, and it keeps objects in the order that I want them kept, and I assume keySet will give a list of the keys in the order I want them.
+Pie Number of slices to send: Send
Right. I meant TreeMap from the start, I just mix those up sometimes. No idea why, since the difference is so clear - one is a Set, the other a Map. They're not even compatible, the only thing they have in common is the Tree part.

That and TreeSet uses a TreeMap internally, but that's not necessary to know.
There's a city wid manhunt for this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 6612 times.
Similar Threads
ConcurrentModificationException
Retrieving Data from HashMap
Database Thread Safety, pls review
Records in Arraylist
Display the sortedMap/TreeMap in descending order: Alternative?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 09:49:14.