I have two String
arrays, let's say:
String[] s1 = {"a","b","c"} String[] s2 = {"c","a","b"}
//these arrays should be equal
I wanted to check their equality in the "cleanest" way.
I tried using Arrays.equals(s1,s2)
but I'm getting a false answer. I guess that this method cares about the elements' order and I don't want that to matter.
Can you please tell me how can I do that in a nice way?
Java: Checking equality of arrays (order doesn't matter)
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
We can use the logic below to compare the equality of two lists using the assertTrue and assertFalse methods. In this first test, the size of both lists is compared before we check if the elements in both lists are the same. As both of these conditions return true, our test will pass.
Python set() method and == operator to compare two lists Python set() method manipulates the data items of an iterable to a sorted sequence set of data items without taking the order of elements into consideration. Further, the == operator is used for comparison of the data items of the list in an element-wise fashion.
In case you do not want to modify the original arrays
Arrays.equals( Arrays.sort( Arrays.copyof(s1,s1.length)), Arrays.sort( Arrays.copyof(s2,s2.length)) );
Arrays.sort() uses an optimized quick sort which is nlog(n) for average but O(n2) in worst case. From the java docs. So the worst case it will O(n2) but practically it will be O(nlogn) for most of the cases.
The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.
Others have suggested sorting the arrays. But since you're looking for the "cleanest" solution, I think the original arrays shouldn't be touched. Hence:
List<String> l1 = new ArrayList<String>(Arrays.asList(s1)); List<String> l2 = new ArrayList<String>(Arrays.asList(s2)); Collections.sort(l1); Collections.sort(l2); boolean outcome = l1.equals(l2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With