the source of the line is provided below, i understand what v.compareTo(w) does but i am curious as to what influence the < 0 has, does it not allow it to return if compareTo returns 1 which is greater than 0? does it not return if anything if compareTo returns 0 because it is equal to 0?

private static boolean less(Comparable v, Comparable w)   
{  
    return v.compareTo(w) < 0; 
}  

Dani AI

Generated

As asked, the "< 0" is simply testing whether v.compareTo(w) produced a negative integer — in other words, "does v come before w in the natural ordering?" If the result is negative the method returns true; if it is zero (equal) or positive (greater) it returns false. was on the right track, but note the important nuance below.

Two practical points to keep in mind that often cause surprises:

  • The compareTo contract says only “negative / zero / positive” — it does not have to be exactly -1 or +1. Any negative int means “less than.”
  • Don’t implement numeric comparisons by subtracting fields (this.x - other.x) because that can overflow. Prefer the built-in compare helpers and chain comparisons to keep compareTo safe and predictable. Example robust patterns:
@Override
public int compareTo(MyType other) {
    int cmp = Integer.compare(this.priority, other.priority);
    if (cmp != 0) return cmp;
    return this.name.compareTo(other.name);
}

Also consider using a generically-typed less helper to avoid raw Comparable:

private static <T extends Comparable<? super T>> boolean less(T v, T w) {
    return v.compareTo(w) < 0;
}

As mentioned, sorting and ordered collections rely on this sign test. If compareTo is inconsistent with equals, or it’s based on mutable fields, TreeSet, TreeMap, and sorting algorithms can behave oddly (missing elements, duplicates, wrong ordering). If unexpected behavior appears, inspect your compareTo implementation first.

Recommended Answers

All 2 Replies

compareTo returns an int...
v<w returns -1
v==w returns 0
v>w returns +1

so if v is less than w, compareTo will return -1, and line 3 will return true. Otherwize compareTo will return 0 or+1, and line 3 will return false.

This is the usual way to sort lists of stuff, and a number of the C++, C#, and Java (as well as other OO languages) use this method to determine where to insert an element in a map or other sorted list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.