Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 637
Jean Y.C. Yang Avatar asked Feb 17 '26 16:02

Jean Y.C. Yang


1 Answers

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.

like image 184
M A Avatar answered Feb 20 '26 04:02

M A