【问题标题】:removing an object from arraylist without changing the index of other objects从arraylist中删除一个对象而不改变其他对象的索引
【发布时间】:2016-04-17 20:39:52
【问题描述】:

所以我需要删除我的循环在数组列表中传递多少次的索引号下的特定对象。

假设我想删除数组列表中索引为 0 的对象

但索引 1 和索引 2(等等)上的对象仍需要与我删除索引 0 之前的索引号相同。

        for (int i = 0; i < 4 i++) {
            player thisPlayer = players.get(i);

            if (not important) {
                players.remove(thisPlayer);
            }
        }

如果玩家 1 需要被移除,其他玩家需要保持相同的索引。

我该怎么办?

【问题讨论】:

  • 您可以将该元素的值设置为null。如您所知,移除元素(除了从末端移除)会将其他元素向前移动。
  • 您可以将元素存储在Map&lt;Integer, Player&gt;;然后您可以删除任意元素(和键)而不影响其他键。
  • 在循环结束后 保持索引不变真的很重要,还是让循环正常工作很重要?
  • 我相信你最好的选择是使用@ElliottFrisch 所说的地图

标签: java arraylist indexing


【解决方案1】:

而不是使用

players.remove(thisPlayer);

你可以尝试一下

players.set(players.indexOf(thisPlayer),null);

【讨论】:

  • 我的想法和这个非常相似,只是我会放一些虚拟播放器之类的,而不是 null
猜你喜欢
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 2013-04-17
  • 2016-02-14
  • 2020-10-07
  • 2018-04-26
  • 2015-08-02
相关资源
最近更新 更多