【问题标题】:Java - Retain data type of value while iterating through HashMapsJava - 在遍历 HashMaps 时保留值的数据类型
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以将您正在迭代的对象强制转换为邻居类。当然,这应该先进行类型检查。

      neighbors values = (neighbors) pair.getValue();
      for (city c: values){
            System.out.println("Test... " + c);
      }
      

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

      1. 类不应以小写字母开头(城市、邻居)
      2. 如果城市只有一个名为“city”的字段(它是一个字符串),您可以只用一个字符串来表示一个城市。
      3. 如果您的邻居类包含仅代表字符串的城市列表,您可以简单地使用 List&lt;String&gt; 来代表城市列表。
      4. 您的地图变为Map&lt;String, List&lt;String&gt;&gt;,这样更易​​于阅读,并且您不需要额外的课程。

      您可以在进行这些更改后像这样进行迭代,而无需强制转换。

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

      【讨论】:

        猜你喜欢
        • 2011-04-04
        • 2013-04-05
        • 2013-09-10
        • 2011-12-12
        • 2014-07-22
        • 2015-08-10
        • 2012-01-10
        • 2020-12-15
        • 1970-01-01
        相关资源
        最近更新 更多