从ArrayList <int []>中删除int []

Dim*_*tri 2 java arraylist

我正在尝试从ArrayList中删除int [].由于我的代码,我只有值,所以我创建数组,然后调用remove();

int[] pos = new int[]{0,1};
positionList.remove(pos);
Run Code Online (Sandbox Code Playgroud)

positionList是相应的ArrayList

这实际上不起作用.还有另一种可能性,比如遍历列表

for (int[] pos : positionList) {
  if (posX == pos[0] && posY == pos[1]) {
    positionList.remove(pos);
    break;
  }
}
Run Code Online (Sandbox Code Playgroud)

pol*_*nts 7

看着posXposY,我很好奇是否ArrayList<Point>有更好的解决方案.

remove找不到数组的原因是因为新数组不是equals已经在集合中的数组.

(new int[0]).equals(new int[0]) // false!
Run Code Online (Sandbox Code Playgroud)

如果您创建自己的Point类,那么您可以@Override equals按照自己的意愿行事,并且可以简单地调用remove(new Point(posX, posY)).

您还应该考虑使用Set<Point> positionList,因为实现提供了更快的删除(O(1)for HashSet,O(log N)for TreeSet).记住@Override hashCode(如果你必须要做的话@Override equals),如果你想使用或需要在其他环境中对点进行排序,请制作Point implements Comparable<Point>(或提供外部Comparator<Point>)TreeSet.

如果您int[]有许多元素并且自定义Point类不适用,那么您可能需要考虑切换到List<Integer>(参见:Effective Java 2nd Edition, 25项:首选列表到数组).它具有equals您需要的行为.它速度较慢,但​​可能仍然足够快.

最后,如果你坚持使用int[],你可以将它包装在你自己的IntArray类中,然后ArrayList<IntArray>改为使用.@Override equalshashCode使用 Arrays.equals(int[], int[]),并hashCode(int[])分别.


Tar*_*Sha 7

从字面上看,使用数组来保存不是项目序列的数据是一种不好的做法.

你的数组实际上是一个拥有两个不同领域的数据持有者.定义坐标类并覆盖Object.equals(Object).那么你的代码将变得更加清晰:

ArrayList<MyPoint> positionList;
// fill list
MyPoint testPos = new MyPoint(0, 1);
positionList.remove(testPos);
Run Code Online (Sandbox Code Playgroud)

你应该猜测如何定义MyPoint..

  • 不要忘记重写Object#hashCode()!http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java (2认同)