【发布时间】:2017-11-07 18:39:25
【问题描述】:
我正在尝试遍历包含以下数据类型的 HashMap:
HashMap<city, neighbors>
city 是一个对象,它包含一个字符串值并在被调用时返回该字符串。这是组成我的city 类的代码:
import java.util.*;
public class city{
String city;
public city(String s){
this.city = s;
}
public String toString() {
return this.city;
}
}
neighbors 是一个包含城市 ArrayList 的对象。这是组成我的neighbors 类的代码:
import java.util.*;
public class neighbors extends ArrayList<city> {
public neighbors (city[] n) {
for (city v : n)
this.add(v);
}
}
我正在尝试使用像这样使用迭代器的常规约定来迭代此哈希映射:
Iterator it = graph.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println("Key :" + pair.getKey()); //prints the city System.out.println("Value :" + pair.getValue()); //prints the neighbors
//for (city c: pair.getValue()){
// System.out.println("Test... " + c);
//}
}
上面的迭代器运行良好,可以很好地打印 getKey 和 getValue 语句。我遇到的问题是我很难通过 Map.Entry 的值(它是一个 ArrayList)进行迭代。我注释掉的 for 循环是完成这项任务的尝试。我意识到getValue() 方法返回一个对象,但我怎样才能保留值的数据类型,即 ArrayList?我是否应该在 neighbors 类中包含另一个方法,该方法遵循 city 类中的 toString() 策略?如何遍历 HashMap 的邻居,以便将它们与其他值进行比较?如果我的问题不清楚,请告诉我,任何提示、修改或建议都会有所帮助。
【问题讨论】:
标签: java arraylist hashmap iterator