簡體   English   中英

Java-在通過HashMap進行迭代時保留值的數據類型

[英]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的鄰居,以便可以將它們與其他值進行比較? 如果我的問題不清楚,請告訴我,任何提示,修改或建議都會有所幫助。

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

我注意到了一些奇怪的事情:

  1. 您不應使用以小寫字母開頭的類(城市,鄰居)
  2. 如果城市只有一個名為“ city”的字段(這是一個字符串),則只需一個String即可代表一個城市。
  3. 如果您的鄰居類包含僅代表字符串的城市列表,則可以簡單地使用List<String>代表城市列表。
  4. 您的地圖將變成Map<String, List<String>> ,它更易於閱讀,並且不需要額外的類。

在進行了這些更改之后,您可以像這樣進行迭代,而無需強制轉換。

for(String city : graph.keySet()){
    for(String neighbor : graph.get(city)){

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM