Comparable接口的用法和实现
来源:互联网 发布:小猪cms9.0源码 可用 编辑:程序博客网 时间:2024/04/30 03:48
Comparable接口的用法和实现
Comparable接口中只有一个方法,
public int compareTo(Object obj);
该方法:
返回0 表示this==obj;
返回正整数表示 this>obj;
返回负数表示this<obj
实现了Comparable接口的类通过实现了compareTo方法从而确定该类对象的排序方式
下面是java中代码的实现方式:
import java.util.Collections;import java.util.ArrayList;import java.util.List;public class TestComparable {public static void main(String[] args) {List<Student> list=new ArrayList<Student>();Student stu1=new Student(1,"张三",100);Student stu2=new Student(3,"张四",80);Student stu3=new Student(2,"张五",90);list.add(stu1);list.add(stu2);list.add(stu3);System.out.println(list);Collections.sort(list);System.out.println(list);}}class Student implements Comparable<Student>{int id;String name;int score;public Student(int id,String name,int score){super();this.id=id;this.name=name;this.score=score;}public String toString(){return id+" "+name+score;}public int compareTo(Student o){if(this.score>o.score){return 1;}else if(this.score<o.score){return -1;}else{return 0;}}}
0 0
- Comparable接口的用法和实现
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- 【转载】Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现
- 实现 Comparable 和 Comparator 接口
- 【Android】广播机制 Broadcast
- eclipse 打开SDK manager报错 A folder failed to be renamed or moved...
- zookeeper配置说明
- Android 兼容 小问题
- 如何区分多个百度地图marker的点击事件
- Comparable接口的用法和实现
- 写给iOS开发初学者
- 深入浅出学Hive——初始Hive
- 02_Flink Streaming SourceFunction
- 移动端数据交互
- java 通过http post方式传参参数json 方式
- java类变量、类方法
- android使用shape stroke描边只保留底部
- Java泛型