I have an ArrayList
containing int[]
.
Assuming Arrays.equals(int[], (a value in the arrayList)) = true
why when I do
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);
}
...
}
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).
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
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).