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?
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.
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.
Joined: Oct 12, 2005
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.
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.