Reputation: 1006
String[] arrays = {"AA", "B"};
Arrays.sort(arrays, (s1, s2)->s1.length()-s2.length());
System.out.println(Arrays.toString(arrays));
It's my test for jdk 8 environment. When s1.length() is bigger than s2.length(), the comparator return a negative number, thus s1 is in front of s2. But the result is ["B", "AA"]. What's wrong ?
When s1.length() is bigger than s2.length(), the comparator return a positive number, thus s2 is in front of s1. So the result is ["B", "AA"]. I just make a foolish mistake.
Upvotes: 0
Views: 816
Reputation: 2732
o1 - object1 in your case s1
o2 - object2 in your case s2
compare method works and returns in this way
-1 : o1 < o2
0 : o1 == o2
+1 : o1 > o2
in your case s1 < s2
so it returns -1 and hence it sorts in ascending order smaller first and then bigger.
public int compare(String s1, String s2) {
System.out.println(s1);
System.out.println(s2);
return s1.length() - s2.length();
}
o/p
B
AA
[B, AA]
in below case if we reverse the return parameteres like below
public int compare(String s1, String s2) {
System.out.println(s1);
System.out.println(s2);
return s2.length() - s1.length();
}
it returns positive number hence sorts based on descending order bigger first and then smaller.
and the o/p is
B
AA
[AA, B]
now return just 0
public int compare(String s1, String s2) {
System.out.println(s1);
System.out.println(s2);
return s2.length() - s2.length();
}
o/p - no sorting happened as it assumes all coming objects are equal.
B
AA
[AA, B]
let me know for any issues.
Upvotes: 2
Reputation: 279910
Let's modify it to log the values
String[] arrays = { "AA", "B" };
Arrays.sort(arrays, (s1, s2) -> {
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
return s1.length() - s2.length();
});
System.out.println(Arrays.toString(arrays));
This prints
s1: B
s2: AA
[B, AA]
B
has a smaller length than AA
, so
return s1.length() - s2.length();
returns a negative value. The sort
method takes that and flips them in the array.
Upvotes: 1
Reputation: 27200
The logic is backward. It sounds like you want to subtract s1.length() from s2.length().
Upvotes: 0