Java 无法在hashmap中迭代2个hashmap
我无法迭代此结构(Java):Java 无法在hashmap中迭代2个hashmap,java,collections,Java,Collections,我无法迭代此结构(Java): HashMap last =新HashMap(); 以下是我将添加到第一个中的两个哈希映射: HashMap<Integer, Integer> arrival = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> departure = new HashMap<Integer, Integer>(); HashMap-arrival=newha
HashMap last
=新HashMap();
以下是我将添加到第一个中的两个哈希映射:
HashMap<Integer, Integer> arrival = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> departure = new HashMap<Integer, Integer>();
HashMap-arrival=newhashmap();
HashMap离开=新建HashMap();
尝试了各种循环,读了几篇文章,但直到现在我还不能把这些点连接起来使之正确
例如,我希望能够在循环中从HashMap中的两个HashMap中获取/打印四个整数值
谢谢大家! 首先,我不认为在另一个
HashMap
中使用HashMap
作为键是个好主意。看起来您是在表示键值对的映射(到达/目的地?),最好只为此创建一个类,然后将该类添加到HashMap
。使用您当前的结构将导致更多的混乱而不是好处
这就是说,有可能通过这个循环
循环HashMap的一种方法是循环trhough它的条目集。因此,如果h
是一个HashMap
,则循环为:
for(Map.Entry<Integer, Integer> entry : h.entrySet)
{
...
}
了解您试图建模的信息会很有帮助-这些整数代表什么?@RoryHunter可能是数字:)scnrI正在制作一个程序,该程序还需要巴士出发和到达的小时/分钟(这就是为什么我需要4个值)。我想在一个数据结构中迭代这四个值,以便以后能够比较它们。谢谢您的回答。由于我认为我没有使用正确的数据结构,我将把我需要与其他对象的值进行比较的四个值放入数组或数组列表中,并在需要时创建一个类来创建这种类型的对象。或者更好的是,使用普通检查将值放入1 HashMap中的双倍值中。
for(Map.Entry<Integer, Integer> entry : h.entrySet)
{
...
}
for(Map.Entry<HashMap<Integer, Integer>, HashMap<Integer, Integer>> entry : last.entrySet())
{
HashMap<Integer, Integer> key = entry.getKey();
for(Map.Entry<Integer, Integer> keyMapEntry : key.entrySet())
{
//Loop through the value HashMap.
//keyMapEntry.getKey() gives the key of the Hashmap that is the key in the
//original Hashmap, keyMapEntry.getValue() gives the value
}
HashMap<Integer, Integer> value = entry.getValue();
for(Map.Entry<Integer, Integer> valueMapEntry : value.entrySet())
{
//Loop through the key HashMap
//valueMapEntry.getKey() gives the key of the Hashmap that is the value in the
//original Hashmap, valueMapEntry.getValue() gives the value
}
}