Skip to content
Advertisement

Custom sorting by two parameters not working correctly

JavaScript

When I input:

JavaScript

the output I get is:

JavaScript

This is not the output that I expect, because my sorting rule is supposed to be when 10001 == 10001 then the ones with smaller second coordinates should be arranged at first.

Advertisement

Answer

I think the issue is Integer caching. For the low numbers, the Integer is cached so != works. For the large numbers, new Integers are used. Use Integer.equals to check for equality.

Change:

JavaScript

Into:

JavaScript

Otherwise you’re comparing the reference not the value.

Another way would be to use the helper methods of the Comparator class.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement