-2

I have to arrays of string

Array 1

Dog
Cat
Mouse
Chicken

Array 2

Cat
Dog
Mouse
Chicken

How can I check if the arrays comtains the same elements (order does not matter)

I guess I should first sort the array and than to compare

I am looking for a boolean answer

EDIT using Java utils is an option for me, I am just not familiar with JAVA enough

3
  • 2
    sort them both, iterate and compare. Commented Dec 16, 2015 at 11:18
  • Two arrays*. If you wanna use ArrayList<String> , then check out my answer. You do not even need to do any sorting. Commented Dec 16, 2015 at 12:17
  • Stultuske made the only good contribution to this question. Every answer is at least sub-par. Take a look at the AssertJ testing library and stop writing miserable unit tests which just output "expected: true, but got false". Commented Jan 11, 2024 at 20:56

6 Answers 6

5

Just sort them both and iterate over the elements to compare them all:

public boolean compareStringArrays(String[] arr1, String[] arr2) {
    if (arr1.length != arr2.length)
        return false;
    
    String[] arr1Copy = arr1.clone();
    String[] arr2Copy = arr2.clone();
  
    Arrays.sort(arr1Copy);
    Arrays.sort(arr2Copy);
    for (int i=0; i<arr1Copy.length; i++) {
        if (!arr1Copy[i].equals(arr2Copy[i]))
            return false;
    }
    return true;
}

Note that I make copies of the arrays here so the original order of the arrays passed in is preserved. There's also an optimisation to check the lengths are the same first, as if one array has more elements than the other they are not equal.

EDIT

you can also use assertArrayEquals() instead of a for loop, but the copy with the separate variables is still necessary because the sort method is a void function

String[] arr1Copy = arr1.clone();
String[] arr2Copy = arr2.clone();
  
Arrays.sort(arr1Copy);
Arrays.sort(arr2Copy);
assertArrayEquals(arr1Copy, arr2Copy);
Sign up to request clarification or add additional context in comments.

1 Comment

Arrays#sort is a void function.
2
ArrayList<String> arrList1 = new ArrayList<>(Arrays.asList(arr1));
ArrayList<String> arrList2 = new ArrayList<>(Arrays.asList(arr2));
Collections.sort(arrList1);
Collections.sort(arrList2);
if (Arrays.equals(arrList1.toArray(), arrList2.toArray())) {
//They have exactly the same elements
}

EDIT: Old answer:

ArrayList<String> arrList1 = new ArrayList<>(Arrays.asList(arr1));
ArrayList<String> arrList2 = new ArrayList<>(Arrays.asList(arr2));
if (arrList1.containsAll(arrList2) && arrList2.containsAll(arrList1)) {
//They have the same elements, not necessarily the same number
}

The top answer will tell you if they both contain the same elements, as well as if they have the same number, Bottom answer will tell you if they both have the same elements, but doesn't tell you if any elements are duplicated

EDIT again: Firstly I posted:

if (arrList1.containsAll(arrList2) && arrList2.containsAll(arrList1)
         && arrList1.size() == arrList2.size())

Checking the size is equal is redundant, since if we have the lists:

Cat
Cat
Dog

and

Cat
Dog
Dog

The expression would evaluate to true, but they do not have exactly the same elements

8 Comments

I think the second condition it's redundant
You should check the size first, so you can "fail fast" if this is false.
@Alist3r not redundant at all, a list can contain all elements of the other and many more!!!!
@JordiCastilla Then the size check would fail.
If you check first the size, then you can compare just if ArrList1 contains all elements of arrList2
|
1

Here is the method:

public boolean compareArray(){
        boolean isSameArray=false;
        String[] arr1={"Dog","Cat","Mouse","Chicken"};
        String[] arr2={"Cat","Dog","Mouse","Chicken"};
        Arrays.sort(arr1);
        Arrays.sort(arr2);

        if(Arrays.equals(arr1, arr2)){
            isSameArray=true;
        }else{
            isSameArray=false;
        }
        return isSameArray;
    }

Comments

0

That is very easy. Just do like this:

ArrayList<String> firstArray=new ArrayList<>();
ArrayList<String> secondArray=new ArrayList<>();

firstArray.add("Dog");
firstArray.add("Cat");
firstArray.add("Mouse");
firstArray.add("Chicken");

secondArray.add("Cat");
secondArray.add("Dog");
secondArray.add("Mouse");
secondArray.add("Chicken");

boolean areEqual=firstArray.containsAll(secondArray);

if(areEqual)
  System.out.println("Voila!");
else
  System.out.println("Oppps!");

8 Comments

surely firstArray could contain all the elements of secondArray and many more, making them not equal.
@jonk I assumed they are with similar size, if not, then the question has no meaning! Your logic gave me cancer.
the question is simply 'do two arrays contain the same elements': if one contains elements that are not in the other, then the answer is no.
based on your code arrays ['A','B','B'] and ['A','A','B'] are equal, which is wrong
@user902383 Technically they are equal. It is a matter of usage. If you ask me, these arrays must be normalized first and then checking if they are same. If you are familiar with math and Sets theory, then what I said is not difficult to undersrand.
|
0

May ways how to do that - probably the best way is to make sort and compare Arrays like Collections(Arrays.sort(arrayToSort)), objects (Arrays.equals(arr1,arr2)) - another way is just iterate over 1st and 2nd array and try to find items one by one (bad idea, not such effective, but good to understand and explain)- something like following:

    String[] arr1={"Dog","Cat","Mouse","Chicken"};
    //String[] arr2={"Dog","Mouse","Chicken"};       //FALSE
    String[] arr2={"Cat","Dog","Mouse","Chicken"}; //TRUE

    boolean foundAll = true;

    if(arr1.length != arr2.length){
        foundAll = false;
    }else{
        for (int i = 0; i < arr1.length; i++) {
            boolean foundActual = false;
            for (int j = 0; j < arr2.length; j++) {
                if(arr1[i].equals(arr2[j])){
                    foundActual = true;
                    break;
                }
                System.out.println("arr1 elem: " + arr1[i] + " arr2 elem: "+ arr2[j]);
            }
            System.out.println("\n");
            if(!foundActual){
                foundAll = false;
                break;
            }

        }
    }
    System.out.println("found all: " + foundAll);
}

Comments

-2
String arr1[] = {//your content goes here};
String arr2[] = {//your content goes here};

Arrays.sort(arr1);
Arrays.sort(arr2);

if(arr1.length != arr2.length){
   retrn false;
}else{
    boolean isSimilar = true;
    for(int i=0; i< arr1.length; i++){
         if(!(arr1[i].equals(arr2[i]))){
            isSimilar = false;
         }
    }
} 
return isSimilar;

3 Comments

You might want to recheck how one should compare Strings in Java.
Thanks Tom! It was my bad...just made the correction :)
you could optimize it little bit, ie you could return false instead assigning value to isSimilar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.