TheScreenSlaver
TheScreenSlaver

Reputation: 3

Behavior of Collections.Sort();

I am trying to understand the sorting behavior of Collections.sort() when a mixture of numbers and letters are present. From conducting research I understand that numbers sort before letters and string sort alphabetically. However, this example is still a bit confusing to me.Collections.sorts ascending. If numbers are sorted first, why would the result not be [8, 30, 3A, FF]?

In this example below the result is [30, 3A, 8, FF]

List<String> hex = Arrays.asList("30", "8", "3A", "FF");
Collections.sort(hex);
System.out.println(hex);

But in this example the result is [30, 40, 50, 60]

  List<String> nums = Arrays.asList ("50", "30", "60", "40");
  Collections.sort(nums);
  System.out.println(nums);

Upvotes: 0

Views: 367

Answers (2)

Youssef NAIT
Youssef NAIT

Reputation: 1530

The way sort works with Strings is starting with the first caracter of the compared elements. If the first caracter of the first element is lower than the first caracter of the second element then the first element is lower and therefor it's on top.

If the first caracters are equal then it procedes with the second, etc...

Examples

"80" compared to "3600" ==> '3' is lower than '8' therefor "3600" is lower than "80"

"88" compard to "830" ==> '8' is equal to '8', then try with the second '3' is lower than '8' so "830" is lower than "88"

Upvotes: 2

Diego Victor de Jesus
Diego Victor de Jesus

Reputation: 3003

The result is 30, 3A, 8, FF because numbers comes first and 3 alphabetically comes before 8. You are not comparing numbers. You are comparing strings. To sort numbers, you need a List<Integer>.

If you want to sort based on two different data types, you need to implement your own sort method inside Collections.sort using a wrapper object.

Upvotes: 1

Related Questions