Java TreeMap 迭代器对于 String 键无法正常工作
我有一个 TreeMap,它将 String 键映射到自定义 City 类。下面是它的实例化方式:
TreeMap<String, City> nameDictionary = new TreeMap<String, City>(new CityNameComparator());
CityNameComparator 实现:
public class CityNameComparator implements Comparator<String>
{
public int compare (String c1, String c2) {
return c1.compareTo(c2);
}
}
我有一个返回迭代器的方法,该迭代器应该按 key-ascii 顺序迭代地图:
public Iterator<City> getNameIterator(){
return nameDictionary.values().iterator();
}
出于某种原因,值按照它们添加到 TreeMap 的顺序返回。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它工作得很好:
输出:
a
b
c
d
It works just fine:
Output:
a
b
c
d
您确定
LinkedHashMap
没有被错误地分配给Map
引用吗?这将保留条目添加到地图的顺序。或者,代码中可能存在添加条目、使用键输入错误值的错误。
迭代条目,并查看地图中的内容:
Are you sure a
LinkedHashMap
hasn't been assigned to theMap
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:
抱歉,愚蠢的错误。我根据其他地方的错误分配了不同的迭代器。现在效果很好。
Sorry, stupid bug. I was assigning a different iterator based on a bug somewhere else. It works fine now.