2

I'm trying to delete an int[] from an ArrayList. Due to my code I only have the values so I'm creating the array and then call remove();

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

positionList is the corrisponding ArrayList

This actually doesn't work. Is there another possibility than iterating through the list like

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

2 Answers2

7

Looking at the posX and posY, I'm curious if something like ArrayList<Point> is a better solution for you.

The reason the remove couldn't find the array is because the new array is not equals to the array already in the collection.

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

If you create you own Point class, then you can @Override equals to behave as you want, and you can simply call remove(new Point(posX, posY)).

You should also consider having a Set<Point> positionList instead, because implementations offer much faster removal (O(1) for HashSet, O(log N) for TreeSet). Remember to @Override hashCode (which you have to do anyway if you @Override equals), and make Point implements Comparable<Point> (or provide an external Comparator<Point>) if you want to use TreeSet or need to sort the points in other contexts.

If your int[] has many elements and a custom Point class is not applicable, then you may want to consider switching to List<Integer> instead (see also: Effective Java 2nd Edition, item 25: prefer lists to arrays). It has the equals behavior that you need. It is slower, but it may still be fast enough.

Lastly, if you insist on using int[], you can just wrap it inside your own IntArray class, and have a ArrayList<IntArray> instead. @Override equals and hashCode to use Arrays.equals(int[], int[]), and hashCode(int[]) respectively.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
7

It's a bad practice to use arrays for holding data that isn't a sequence of items, literally.

Your array is actually a data holder with two distinct feilds. Define a coordinates class and override Object.equals(Object). Then your code will become much cleaner:

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

You should be guessing how to define MyPoint..

Tareq Sha
  • 515
  • 4
  • 14
  • or better yet, use the actual Point2D or Point class in the JDK, http://java.sun.com/javase/6/docs/api/java/awt/geom/Point2D.html – basszero Mar 05 '10 at 17:04
  • 2
    Don't forget to override Object#hashCode() too! http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java – Alex Marshall Mar 05 '10 at 17:19
  • There are two issues with Point2D. First it is abstract so Dimitri would need to write a class anyway. Second it uses doubles while Dimitri uses integers.. My general point was using data structures instead of arrays. – Tareq Sha Mar 05 '10 at 19:42