java - Does Comparator work differently with wrapper class? -


I fail to sort student ID from database, after a long time it detects that it is incorrectly Why is the solution, I have concluded that this Comparator works differently with the rapper class?

  Public Class comparator demo {public static zero main (string [] args) {Comparator & lt; Integer & gt; IDComparator = new comparison & lt; Integer & gt; () {@ Override Public Int Comparison (integer first ID, integer sec ID) {return firstID & lt; SecondID? (-1): (first id == sec id? (0): (1)); }}; System.out.println (IDComparator.compare (new integer (1), new integer (1))); // print1 system.out.printLN (IDComparator.compare ((1), (1))); // print}}  

What's going on here?

In Java, when comparing two references to == By using, the result will be true and if only two references point to the same exact object, then when you enter new integer (1) to new integer false

primitives (like int ) are compared with (1) , == When using == to compare with, when values ​​are equal, return true Ega

use a solution firstID.equals (secondID)

For more information

UPDATE

As mentioned by JBNizet, you can return

FirstID & lt; SecondID? (-1): (first id == sec id? (0): (1));

with

back to firstID.compareTo (secondID);

The code that makes reading a lot easier and definitely uses the right comparison.


Comments

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -