3
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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so how to do? change contains to equals, the result is still "false". I need to check if the ArrayList "has" the String Array
@JeanYang updated my answer. Again you can't call equals on arrays as it checks the reference equality, not the object equality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.