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;
}
}
Looking at the
posXandposY, I’m curious if something likeArrayList<Point>is a better solution for you.The reason the
removecouldn’t find the array is because the new array is notequalsto the array already in the collection.If you create you own
Pointclass, then you can@Override equalsto behave as you want, and you can simply callremove(new Point(posX, posY)).You should also consider having a
Set<Point> positionListinstead, because implementations offer much faster removal (O(1)forHashSet,O(log N)forTreeSet). Remember to@Override hashCode(which you have to do anyway if you@Override equals), and makePoint implements Comparable<Point>(or provide an externalComparator<Point>) if you want to useTreeSetor need to sort the points in other contexts.If your
int[]has many elements and a customPointclass is not applicable, then you may want to consider switching toList<Integer>instead (see also: Effective Java 2nd Edition, item 25: prefer lists to arrays). It has theequalsbehavior 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 ownIntArrayclass, and have aArrayList<IntArray>instead.@Override equalsandhashCodeto useArrays.equals(int[], int[]), andhashCode(int[])respectively.