Hello

Next target

Akka, SpringMVC

Xiaohan's programmer life

A student in BUPT and UF. I would like to focus on SpringMVC and AKKA in the next half year.

导航

java comparable<T>

Posted on 2013-04-23 11:17  Xiaohan S.  阅读(122)  评论(0)    收藏  举报

To implement such a class, we should firstly implement one method named compareTo()(int). We have better implement (int)hashCode() and equals() (boolean) to make sure that the same object returns the same hash code.

After that, we may use Array.sort() or Collections.sort to rank, or even can apply in Treemap or Treeset. 

class student implements Comparable<students>
{
  public grades;
  public lastgrades;
  @override
  public int compareTo(students other)
  {
    if (other.grades>this.grades)
      return 1;
    else if (other.grades==this.grades)
    {
      if(other.lastgrades>this.grades)
      return 1;
      else if (other.lastgrades==this.grades)
      return 0;
      else 
      return -1;
    }
    else return -1;
  }
}

But in general, we use private mode to represent the attribute.

So we use a method to get the value back, and we will not discuss it here. And we have not initiallize the attribute in the construction.

 

public int compareTo(student other)
{
int t=other.grade-this.grade;
if (t!=0)
return t;
else
return other.name.compareTo(this.name) ;
}

 compareTo here represents the method in STRING but not the comparable. This is quite confusing but if you use the right type at the beginning the computer will not mistakenly take it. This is also called overload.

Using Array.sort() can automatically sort all objects in the class under your rule. 

public class mm
{
    public static void main(String[] args) {
       student[] stu = { new Person(8,3), new Person(8,4 ),
              new Person(7, 6 ), new Person(9,3 ),
              new Person(4, 6 ), new Person(4, 4 ),
              new Person(5, 7 ) };//the first one represents the grades.
       Arrays.sort (stu);
}

  now if you print the stu, you will get an ordered result.