第十二条: Comparable和Comparator

来源:互联网 发布:最容易上手的编程语言 编辑:程序博客网 时间:2024/06/05 03:09

  

       一个是对于自定义对象内部进行排序, 一个是通过在外部进行排序。  其他的区别并不是很大, 但是感觉写在外部的方式,扩展性和易读性都相对好一些。 具体列子代码如下:

 

package cn.stu;public class Student implements Comparable{public  String  name;public  double  score; @Overridepublic int compareTo(Object other) {if(other instanceof Student){Student stu = (Student)other;if(this.score > stu.score){return 1; }else if(this.score < stu.score){return -1; }}return 0;}@Overridepublic String toString() { return name+"分数--->"+score;}}

package cn.stu;import java.util.Comparator;public class Worker{public String name;public double price; @Overridepublic String toString() { return  "名字:"+name+",工资---->"+price;}}

package cn.stu;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Main { @SuppressWarnings("unchecked")public static void main(String[] args) { Student stu_A = new Student();stu_A.name = "小强";stu_A.score = 50;  Student stu_B = new Student();stu_B.name = "小发";stu_B.score = 80; int result = stu_A.compareTo(stu_B);System.out.println(result);List<Student> stuList = new ArrayList<Student>();Student entity = null;List<Worker> workerList = new ArrayList<Worker>();Worker worker = null;for(int  i = 0; i<10; i++){  entity = new Student();  entity.name = i+"小笑";   entity.score = (int)(Math.random()*100);  stuList.add(entity);    worker = new Worker();  worker.name = i + "小凯";  worker.price = (int)(Math.random()*10000);  workerList.add(worker);} Comparator comparator = new Comparator<Worker>() {@Overridepublic int compare(Worker o1, Worker o2) { return o1.price > o2.price ? -1 :(o1.price == o2.price ? 0 : 1);}};Collections.sort(stuList);// entity.compareTo(other)Collections.sort(workerList, comparator);// comparator.compare(o1, o2) 单个比较。for(int i = 0; i<stuList.size(); i++){System.out.println(stuList.get(i));}for(int i = 0; i<workerList.size(); i++){System.out.println(workerList.get(i));} }}

运行结果如下:

-1
2小笑分数--->0.0
3小笑分数--->27.0
4小笑分数--->51.0
7小笑分数--->55.0
8小笑分数--->70.0
1小笑分数--->85.0
9小笑分数--->93.0
0小笑分数--->97.0
6小笑分数--->97.0
5小笑分数--->98.0
名字:5小凯,工资---->9646.0
名字:2小凯,工资---->9445.0
名字:3小凯,工资---->9123.0
名字:7小凯,工资---->5825.0
名字:9小凯,工资---->4973.0
名字:1小凯,工资---->3553.0
名字:8小凯,工资---->3152.0
名字:6小凯,工资---->2559.0
名字:0小凯,工资---->290.0
名字:4小凯,工资---->134.0


0 0
原创粉丝点击