VOOZH about

URL: https://www.geeksforgeeks.org/java/how-compare-method-works-in-java/

⇱ How compare() method works in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How compare() method works in Java

Last Updated : 11 Jul, 2025

Prerequisite:Comparator Interface in Java, TreeSet in Java
The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 

  • 0: if (x==y)
  • -1: if (x < y)
  • 1: if (x > y)

Syntax:

public int compare(Object obj1, Object obj2)

where obj1 and obj2 are the two objects to be compared using compare() method. 

Example:

To show working of compare() method using Integer Class.


Output
-1
0
1

How is the return value evaluated:

The internal working of the compare() method can be visualized with the help of below pseudocode:

Visualizing the compare() method with this approach:


Output
-1
0
1

Various possible implementations of compare() method

public int compare(Object obj1, Object obj2)
{
Integer I1 = (Integer)obj1; // typecasting object type into integer type
Integer I2 = (Integer)obj2; // same as above ..
// 1.
return I1.compareTo(I2); // ascending order [0, 5, 10, 15, 20]
// 2.
return -I1.compareTo(I2); // descending order [20, 15, 10, 5, 0]
// 3.
return I2.compareTo(I1); // descending order [20, 15, 10, 5, 0]
// 4.
return -I2.compareTo(I1); // ascending order [0, 5, 10, 15, 20]
// 5.
return +1; // insertion order [10, 0, 15, 5, 20, 20]
// 6.
return -1; // reverse of insertion order [20, 20, 5, 15, 0, 10]
// 7.
return 0; // only first element [10]
}
Comment
Article Tags:
Article Tags: