Jean Y.C. Yang
Jean Y.C. Yang

Reputation: 4552

JAVA ArrayList : How to know whether it contains a String array 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);
            }
        }
    }

Console said "false." I have an ArrayList and I can't check whether it contains a particular String array. How to do and why?

Upvotes: 3

Views: 125

Answers (1)

M A
M A

Reputation: 72884

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.

Upvotes: 2

Related Questions