JAVA ArrayList: how to know if it contains an array of strings or not?
import java.util.ArrayList;
public class Test {
public static void main (String[] args){
ArrayList<String[]> a = new ArrayList<String[]>();
a.add(new String[]{"one", "abc"});
a.add(new String[]{"two", "def"});
if(a.contains(new String[]{"one", "abc"})){
System.out.println(true);
}else{
System.out.println(false);
}
}
}
The console said "false". I have an ArrayList and I cannot check if it contains a specific String array. How to do this and why?
source to share
contains
checks the conformity of an object using a method implementation equals
. However, for arrays, it is equals
equivalent to reference equality. That is, it is array1.equals(array2)
translated into array1 == array2
.
In the example above new String[]{"one", "abc"})
, passed to the method contains
will create a new array that is different from the one that was originally added to ArrayList
.
One way to do the check is to iterate over each array in ArrayList
and check for equality with Arrays.equals(array1, array2)
:
for(String[] arr : a) {
if(Arrays.equals(arr, new String[]{"one", "abc"})) {
System.out.println(true);
break;
}
}
Another way is to use ArrayUtils.isEquals
from Apache commons-lang
.
source to share