[英]Java - Retain data type of value while iterating through HashMaps
我正在嘗試遍歷包含以下類型的數據類型的HashMap:
HashMap<city, neighbors>
city
是一個包含String值並在被調用時返回字符串的對象。 這是組成我的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()
方法返回一個Object,但是如何保留Value的數據類型(即ArrayList)呢? 我是否應該在我的neighbors
類中包括另一個遵循city
類的toString()
策略的方法? 我如何遍歷HashMap的鄰居,以便可以將它們與其他值進行比較? 如果我的問題不清楚,請告訴我,任何提示,修改或建議都會有所幫助。
對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);
}
}
您可以將要迭代的對象轉換為鄰居類。 當然,應該先進行類型檢查。
neighbors values = (neighbors) pair.getValue();
for (city c: values){
System.out.println("Test... " + c);
}
我注意到了一些奇怪的事情:
List<String>
代表城市列表。 Map<String, List<String>>
,它更易於閱讀,並且不需要額外的類。 在進行了這些更改之后,您可以像這樣進行迭代,而無需強制轉換。
for(String city : graph.keySet()){
for(String neighbor : graph.get(city)){
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.