2010-03-05 59 views
2

我想从ArrayList中删除一个int []。 由于我的代码,我只有值,所以我创建数组,然后调用remove();从ArrayList中删除int [] <int[]>

int[] pos = new int[]{0,1}; 
positionList.remove(pos); 

positionList是corrisponding ArrayList的

这实际上是行不通的。是否有另一种可能性,不是通过列表迭代像

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

回答

7

纵观posXposY,我很好奇,如果像ArrayList<Point>对你是一个更好的解决方案。

remove找不到阵列的原因是因为新阵列不是equals到已经在集合中的阵列。

(new int[0]).equals(new int[0]) // false! 

如果你创建你自己的Point类,那么你可以@Override equals的行为,只要你想,你可以简单地调用remove(new Point(posX, posY))

你也应该考虑有Set<Point> positionList代替,因为实现(TreeSetO(1)HashSetO(log N))提供了更快的去除。如果您想使用TreeSet或需要在其他上下文中对点进行排序,请记住@Override hashCode(如果您使用@Override equals,您必须执行此操作),并且使Point implements Comparable<Point>(或提供外部Comparator<Point>)。

如果您int[]有许多元素和自定义Point类是不适用的,那么你可能要考虑切换到List<Integer>代替(参见:有效的Java第二版,第25项:宁愿名单阵列)。它具有您需要的equals行为。速度较慢,但​​速度可能仍然很快。

最后,如果您坚持使用int[],您可以将其包装在您自己的IntArray类中,并使用ArrayList<IntArray>代替。 @Override equalshashCode分别使用Arrays.equals(int[], int[])hashCode(int[])

+1

+1使用,而不是一个列表的HashSet的建议。 ArrayList当然是ad hoc删除的最低效的集合。 – 2010-03-05 17:04:31

+0

是的,我试图在我的回答中以递增的方式涵盖所有相关基础。 – polygenelubricants 2010-03-05 17:06:35

+1

+1这么多级别。 – 2010-03-05 17:17:23

7

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

你的数组实际上是一个拥有两个不同域的数据持有者。 定义坐标类并覆盖Object.equals(Object)。然后,你的代码会变得更加干净:

ArrayList<MyPoint> positionList; 
// fill list 
MyPoint testPos = new MyPoint(0, 1); 
positionList.remove(testPos); 

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

+0

或更好,请使用JDK中实际的Point2D或Point类,http://java.sun.com/javase/6/docs/api/java/awt/geom/Point2D。html – basszero 2010-03-05 17:04:41

+2

不要忘记重写Object#hashCode()了! http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java – 2010-03-05 17:19:09

+0

Point2D有两个问题。首先它是抽象的,所以Dimitri无论如何都需要写一个类。其次它使用双打,而迪米特里使用整数.. 我的一般观点是使用数据结构,而不是数组。 – 2010-03-05 19:42:27