Delete int[] from ArrayList<int[]>
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] && p开发者_运维问答osY == pos[1]) {
positionList.remove(pos);
break;
}
}
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.
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
..
精彩评论