-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

user829174
  • 6,132
  • 24
  • 75
  • 125

6 Answers6

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: this is 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 obviously not equal.

EDIT

you can also use Arrays.equals() instead of a for loop (which I originally didn't think of but seems obvious now), so you could achieve this with a one-liner:

Arrays.equals(Arrays.sort(arr1.clone()), Arrays.sort(arr2.clone()));
jonk
  • 1,494
  • 11
  • 13
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

dbrown93
  • 344
  • 2
  • 10
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;
    }
Mukesh
  • 182
  • 1
  • 2
  • 10
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!");
lonesome
  • 2,503
  • 6
  • 35
  • 61
  • surely `firstArray` could contain all the elements of `secondArray` and many more, making them not equal. – jonk Dec 16 '15 at 12:39
  • @jonk I assumed they are with similar size, if not, then the question has no meaning! Your logic gave me cancer. – lonesome Dec 16 '15 at 12:42
  • 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. – jonk Dec 16 '15 at 12:48
  • 3
    based on your code arrays ['A','B','B'] and ['A','A','B'] are equal, which is wrong – user902383 Dec 16 '15 at 12:58
  • @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. – lonesome Dec 16 '15 at 13:50
  • @jonk If you rely too much to what is in the question, the same question gave an example and using this example, i gave this answer. Now what are you trying to say? – lonesome Dec 16 '15 at 13:52
  • @Ionesome i'm familiar with sets, but let me remind you sets and arrays are different data structures and work on different principles. If question would be about sets not arrays, your point would be valid. Another thing, you mention in comment arrays should be normalized first, I think it will be worth to add this to your answer. And last thing, as you mention set theory fact `A contains all element of B` which you check in your code, does mean `B contains all elements of A` hence even if you convert them to sets your function still might return incorrect result – user902383 Dec 16 '15 at 14:41
  • @lonesome I don't know why you are getting so aggressive and I don't know why you have failed to understand the question: it specifically states 'How can I check if the arrays contain the same elements'. Arrays, not sets. No duplicates. The **same** elements. Your answer does **not** do that. This has been pointed out to you, both with the lack of consideration for duplicates and for other elements. – jonk Dec 16 '15 at 20:43
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);
}
xxxvodnikxxx
  • 1,270
  • 2
  • 18
  • 37
-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;
Atul Yadav
  • 1,992
  • 1
  • 13
  • 15