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.
Your code:
return this.val>other.val?-1:1;
It's means thatif (this.val>other.val) {
More simply:return -1
}else{
return 1;
}
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.If this.val > other.val, method compareTo() returns negative number. It means that this will be put before other.