问题
I have an ArrayList
containing int[]
.
Assuming Arrays.equals(int[], (a value in the arrayList)) = true
why when I do arrayOfInts.contains(int[])
is this false?
I assume it is because of the same reason that (int[] == (a value in the arrayList)) = false
but should I be getting this error?
Can I correct it somehow?
TL;DR: Can I use Arraylist.contains() for int[]
EDIT:
ANSWER (if anyone searches this in the future here's the comparison code I made as a solution):
private boolean arraylistContains(int[] comparison, ArrayList<int[]> arrayListToCompare){
for(int[] values: arrayListToCompare){
if (Arrays.equals(comparison, values)){
return true;
}
}
return false;
}
回答1:
A list of arrays stores only the references to the arrays, not their content, therefore contains()
is only able to say, if the list contains the exact reference to the array you input. It doesn't evaluate the contents of the array.
If you need to check, if the list contains an array with specific values, you will have to iterate over the list and use Arrays.equals(arr1, arr2).
回答2:
You cannot, unfortunately. I would probably wrap the array in another object and put that in the list instead. Something like (totally untested):
public class IntArrayWrapper {
private final int[] intArray;
public IntArrayWrapper(int[] intArray) {
this.intArray = intArray;
}
@Override
public int hashCode() {
return Arrays.hashCode(intArray);
}
@Override
public boolean equals(Object other) {
return other instanceof IntArrayWrapper && Arrays.equals(this.intArray, ((IntArrayWrapper) other).intArray);
}
}
Then, if you decide in the future to replace your ArrayList with a HashSet, for example, it will be simple (and you might get some nice performance gains).
回答3:
REFER -> https://stackoverflow.com/a/106351/1897935
ArrayList<Object> list = ...;
for (Object o : list) {
if (o.getClass().equals(Integer.TYPE)) {
handleInt((int)o);
}
else if (o.getClass().equals(String.class)) {
handleString((String)o);
}
...
}
回答4:
You cannot because
int[] a = { 1,2,3 };
int[] b = { 1,2,3 };
List<int[]> list = new ArrayList<int[]>();
list.add(a);
list.contains(b); // is false
a
is not equal b
, it means a.equals(b)
will return false
. Method Collection.contans(Object)
is using equals
to check if an abject is already in a collections. So if a.equals(b)
is false
you get that the array is not in the collection even if they looks the same.
There is an exception. If they are really the same object contains
will return true
. See below:
int[] a = { 1,2,3 };
List<int[]> list = new ArrayList<int[]>();
list.add(a);
list.contains(a); // is true
来源:https://stackoverflow.com/questions/21969714/how-can-i-find-if-my-arraylist-of-int-contains-an-int