Reputation: 2133
I have a TreeMap that maps String keys to a custom City class. Here is how it is instantiated:
TreeMap<String, City> nameDictionary = new TreeMap<String, City>(new CityNameComparator());
CityNameComparator implementation:
public class CityNameComparator implements Comparator<String>
{
public int compare (String c1, String c2) {
return c1.compareTo(c2);
}
}
I have a method that returns an iterator that should iterate through the map in key-ascii order:
public Iterator<City> getNameIterator(){
return nameDictionary.values().iterator();
}
For some reason the values are returned in the order they were added to the TreeMap. Any ideas?
Upvotes: 0
Views: 6090
Reputation: 2133
Sorry, stupid bug. I was assigning a different iterator based on a bug somewhere else. It works fine now.
Upvotes: 0
Reputation: 567
It works just fine:
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeMap;
public class test2 {
public static class City {
public final String m_name;
public City(String aName) {
m_name = aName;
}
}
public static class CityNameComparator implements Comparator<String>
{
public int compare (String c1, String c2) {
return c1.compareTo(c2);
}
}
public static class CityMap {
TreeMap<String, City> nameDictionary = new TreeMap<String, City>(new CityNameComparator());
public Iterator<City> getNameIterator(){
return nameDictionary.values().iterator();
}
public City put(String aName) {
return nameDictionary.put(aName, new City(aName));
}
}
public static void main(String[] args) {
CityMap cityMap = new CityMap();
cityMap.put("d");
cityMap.put("b");
cityMap.put("c");
cityMap.put("a");
for (Iterator<City> cities = cityMap.getNameIterator(); cities.hasNext(); ) {
City city = cities.next();
System.out.println(city.m_name);
}
}
}
Output:
a
b
c
d
Upvotes: 3
Reputation: 269667
Are you sure a LinkedHashMap
hasn't been assigned to the Map
reference by mistake? That would preserve the order the entries were added to the map.
Or perhaps there is a bug in the code that is adding entries, putting the wrong value with a key.
Iterate over the entries, and see what is in the map:
for (Map.Entry<String, City> e : dictionary.entrySet())
System.out.println(e.getKey() + " --> " + e.getValue());
Upvotes: 0