Comparable接口测试

Comparable接口测试

在写某些程序的时候我们往往需要排序,特别是是对容器进行排序的时候,往往是很麻烦的,这时候我们就可以继承Comparable接口中的compareTo方法来进行排序。

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public  class ComparableTest implements Comparable<ComparableTest>{
private int id;
private String name;
private int age;
private String sex;


public ComparableTest(int id, String name, int age, String sex) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}


public static void main(String[] args) {
// TODO Auto-generated method stub
Map<ComparableTest,String> map=new TreeMap<>();
map.put(new ComparableTest(35,"张三",25,"男"),"123");
map.put(new ComparableTest(25,"李四",20,"男"),"456");
map.put(new ComparableTest(12,"王小花",18,"女"),"678");
map.put(new ComparableTest(12,"李小四",14,"男"),"910");
for(ComparableTest key:map.keySet()) {
System.out.println(key+"---"+map.get(key));
}


}

@Override
public String toString() {
// TODO Auto-generated method stub
return "id:"+id+",name:"+name+",age:"+age+",sex:"+sex;
}
@Override
public int compareTo(ComparableTest o) { //负数:小于,0:等于,正数:大于
// TODO Auto-generated method stub
if(this.id>o.id)
return 1;
else if(this.id<o.id)
return -1;
else if(this.age>o.age)
return 1;
else if(this.age<o.age)
return -1;
else
return 0;
}

}

运行结果

id:12,name:李小四,age:14,sex:男—910
id:12,name:王小花,age:18,sex:女—678
id:25,name:李四,age:20,sex:男—456
id:35,name:张三,age:25,sex:男—123

原创技术分享,您的支持将鼓励我继续创作
0%