Блог пользователя hari6988

Автор hari6988, 13 лет назад, По-английски

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.

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

13 лет назад, # |
Rev. 2   Проголосовать: нравится +4 Проголосовать: не нравится

>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 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится
    if we use return other.val-this.val , it will put "other" before "this" if this.val>other.val, right ?
    • 13 лет назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

      No.

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