hari6988's blog

By hari6988, 13 years ago, In English

Hi,
I am having a little difficulty in understanding how the values are inserted into the TreeMap in a sorted order. Take a look at this code in a class that implements comparable

public int compareTo(STR other)
{
   if(this.val==other.val) return this.team.compareTo(other.team);
  return this.val>other.val?-1:1;
}

I dont understand why -1 is returned when this.val>other.val (The problem requires that the objects be sorted in decreasing order of values). Also, what is returned by
return this.team.compareTo(other.team)  /* team is a String data

Also, the method compareTo is not called anywhere. So,where do the above return statements go to ? Does this occur implicitly whenever values are inserted into the TreeMap? Thanks for the help.

  • Vote: I like it
  • 0
  • Vote: I do not like it

13 years ago, # |
Rev. 2   Vote: I like it +4 Vote: I do not like it

>I dont understand why -1 is returned when this.val>other.val
Your code:

return this.val>other.val?-1:1;

It's means that

if (this.val>other.val) {
return -1
}else{
return 1;
}

More simply:

return other.val-this.val

>Also, what is returned by
>return this.team.compareTo(other.team)

Method String.CompareTo(String arg) return -1 if current string < arg in lexicographical order. Retun 0 if strings are equal in lexicographical order, else 1.

Method public int compareTo(STR other) needed for work of TreeMap for keys compare if keys are complex Objects and we want to compare them by their fields. Read about R-B trees and other type of trees for advanced information.
  • 13 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    if we use return other.val-this.val , it will put "other" before "this" if this.val>other.val, right ?
    • 13 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      No.

      If this.val > other.val, method compareTo() returns negative number. It means that this will be put before other.