luckForever

Comparable接口的作用

之前Arrays类中存在sort()方法,此方法可以直接对对象数组进行排序。

 

Comparable接口

可以直接使用java.util.Arrays类进行数组的排序操作,但对象所在的类必须实现Comparable接口,用于指定排序接口。

Comparable接口的定义如下:

public  interface  Comparable{

        public  int compareTo(T  o);

}

此方法返回一个int类型的数据,但是此int的值只能是一下三种:

1:表示大于

-1:表示小于

0:表示相等

 

要求:定义一个学生类,里面有姓名,年龄,成绩三个属性,要求按成绩由高到低排序,如果成绩相等,则按照年龄由低到高排序。

[java] package com.itmyhome; 
 
import java.util.Arrays; 
 
class Student implements Comparable{ 
    private String name; 
    private int age; 
    private float score; 
     
    public Student(String name,int age,float score){ 
        this.name = name; 
        this.age = age; 
        this.score = score; 
   
     
    @Override 
    public int compareTo(Student stu) {  //覆写compareTo方法实现排序规则的应用  
        if(this.score>stu.score){ 
            return -1; 
        }else if(this.score
            return 1; 
        }else{ 
            if(this.age>stu.age){ 
                return 1; 
            }else if(this.age
                return -1; 
            }else{ 
                return 0; 
           
       
   
     
    public String toString(){ 
        return "姓名:"+this.name+", 年龄:"+this.age+", 成绩:"+this.score; 
   
     

分类:

技术点:

相关文章: