我正在尝试遍历包含以下类型数据类型的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的邻居,以便将它们与其他值进行比较?如果我的问题不清楚,请告诉我,任何提示、修改或建议都会有所帮助。
发布于 2017-11-08 02:42:55
对Iterator和Map.Entry变量使用参数化类型,而不是原始类型:
Iterator<Map.Entry<city, neighbors>> it = graph.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<city, neighbors> pair = 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);
}
}发布于 2017-11-08 03:04:46
您可以将正在迭代的对象强制转换为neighbors类。当然,这之前应该有一个类型检查。
neighbors values = (neighbors) pair.getValue();
for (city c: values){
System.out.println("Test... " + c);
}我注意到了一些奇怪的事情:
List<String>来表示城市列表即可。在完成这些更改后,您可以像这样进行迭代,而不需要强制转换。
for(String city : graph.keySet()){
for(String neighbor : graph.get(city)){
}
}https://stackoverflow.com/questions/47165209
复制相似问题