Sobes.tech
Junior — Middle

How to interpret the return value -1 in the compare method in Java?

sobes.tech AI

Answer from AI

In Java, the compare method is typically used in the Comparator or Comparable interfaces to compare two objects. A return value of -1 indicates that the first object is less than the second.

Specifically:

  • If the method returns a negative number (e.g., -1), the first object is considered less than the second.
  • If it returns 0, the objects are equal.
  • If a positive number, the first object is greater than the second.

Example:

@Override
public int compare(String s1, String s2) {
    return s1.length() - s2.length(); // if the length of s1 is less than s2, a negative number (-1) will be returned
}

Here, if the length of s1 is less than the length of s2, the method will return a negative number, for example -1, which means s1 is less than s2.

How to interpret the return value -1 in the compare… - sobes.tech