您的位置:首页 > 编程语言 > Java开发

java中Comparable接口(比较器)的使用

2016-03-29 10:30 127 查看
/*比较器的使用*/

class Student implements Comparable<Student>{ //指定泛型类型为Student

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;

}

public String toString(){

return name +"\t\t"+age+"\t\t"+score;

}

public int compareTo(Student stu){

if(this.score > stu.score){

return -1;

}else if(this.score < stu.score){

return 1;

}else{

if(this.age > stu.age){

return 1;

}else if(this.age <stu.age){

return -1;

}else{

return 0;

}

}

}

}

public class ComparableDemo {

public static void main(String[] args) {

// TODO Auto-generated method stub

Student stu[] = {new Student("张三",20,20.0f),

new Student("李四",30,23.5f),

new Student("王五",30,32.4f),

new Student("赵六",34,34.3f)

};

java.util.Arrays.sort(stu);

for(int i=0; i<stu.length; i++){

System.out.println(stu[i]);

}

}

}

/*

运行结果:

赵六 34 34.3

王五 30 32.4

李四 30 23.5

张三 20 20.0

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: