【问题标题】:iterating through hashmaps and accessing its elements遍历哈希图并访问其元素
【发布时间】:2014-11-22 03:33:35
【问题描述】:

我想遍历一个哈希图。我知道我可以轻松使用 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 很容易找到任何点,因为我的地图的多边形是由 id 列表组成的。

【问题讨论】:

  • 每对两点?还是只有两个具体点?您可以多次致电myMap.get
  • 是的,遍历每一对两点。 @LouisWasserman

标签: java iterator hashmap


【解决方案1】:

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

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

我不知道你使用的是什么类型的变量,因此......你应该把你正在使用的类型放在那里。

【讨论】:

  • 这非常有效。虽然我花了一点时间来理解它的逻辑。谢谢。这项工作背后的逻辑很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-19
  • 2014-06-01
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多