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);
}
}
}
Console said "false." I have an ArrayList and I can't check whether it contains a particular String array. How to do and why?
contains checks object equality using the equals method implementation. For arrays, however, equals is equivalent to reference equality. I.e. array1.equals(array2) translates to array1 == array2.
In the above, the new String[]{"one", "abc"}) passed to the contains method will create a new array which will be different than the one originally added to the ArrayList.
One way to do the check is to loop over each array in the ArrayList and check the equality using 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With