迭代哈希映射并访问其元素

时间:2014-11-22 03:33:36

标签: java iterator hashmap

我想迭代一个hashmap。我知道我可以轻松使用entrySet。但问题是我想一次访问两个元素。

示例:

HasHMap<Integer,Point> myMap = new HashMap<Integer,Point>();
          //I add some points to the map where integer is the id of that point

我希望能够一次访问两个元素,因此我可以使用Graphics drawLine方法。

我不确定是否有办法。

注意:我正在使用一个hashmap,因为它很容易通过id找到任何一点,因为我的map的多边形是由id列表组成的。

1 个答案:

答案 0 :(得分:0)

只需在循环中设置一个单独的Map.Entry变量即可。然后你可以使用drawTo使用这个变量和循环变量。

Map.Entry<?, ?> oldValue = null;
for(Map.Entry<?, ?> newValue : values) {
   if (oldValue != null) {
      doSomethingWithBoth(oldValue, newValue);
   }
   oldValue = newValue;
}

我不会&#39;知道你正在使用什么样的变量?....你应该把你正在使用的类型放在那里。