gpt4 book ai didi

Java TreeMap 迭代器对于 String 键无法正常工作

转载 作者:行者123 更新时间:2023-12-02 00:54:20 25 4
gpt4 key购买 nike

我有一个 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 的顺序返回。有什么想法吗?

最佳答案

它工作得很好:

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);
}
}
}

输出:

一个

b

c

关于Java TreeMap 迭代器对于 String 键无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1517108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com