Comparable&Comparator

1)Comparable位于java.lang下;Comparator位于java.util下;

2)Comaparable是一个对象本身就已经支持自比较所需实现的接口(如String ,Integer自己就可以完成比较操作,已经实现了Camparable接口);自定义的类,要在容器如list中实现排序,可以实现Camparable接口。

package test;

import java.util.Arrays;
import java.util.Random;

public class EmployeeSortTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Employee[] staff = new Employee[3];
		staff[0] = new Employee("harry Hacker", 135000);
		staff[1] = new Employee("carl cracke", 75000);
		staff[2] = new Employee("tony Tester", 38000);
		Arrays.sort(staff); // sort方法可以实现对对象数组排序,但是必须实现 Comparable接口
		/*
		 * Comparable接口原型为: public interface Comparable<T> { int compareTo(T
		 * other);//接口的中方法自动属于public方法 }
		 */
		for (Employee e : staff)
			System.out.println("id=" + e.getId() + "  name=" + e.getName()
					+ ".salary=" + e.getSalary());
	}
}

/*
 * 因为要实现对Employee对象的排序,所以在Employee类中要实现Comparable接口, 也就是要实现comepareTo()方法
 */
class Employee implements Comparable<Employee> {
	public Employee(String n, double s) {
		name = n;
		salary = s;
		Random ID = new Random();
		id = ID.nextInt(100000001);
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public double getSalary() {
		return salary;
	}

	public void raiseSalary(double byPercent) {
		double raise = salary * byPercent / 100;
		salary += raise;
	}

	public int compareTo(Employee other) {
		if (id < other.id) // 这里比较的是什么 sort方法实现的就是按照此比较的东西从小到大排列
			return -1;
		if (id > other.id)
			return 1;
		return 0;
	}

	private int id;
	private String name;
	private double salary;
}

3)Comparator是一个专用比较器,当这个对象不支持自比较,或者自比较不能满足要求时,或者无法改变原有类时,可以写一个比较器来实现两个对象之间的比较。使用步骤主要可以分为三步:

     首先创建一个Comparator接口的实现类,并赋值给一个对象,将Comparable接口作为参数传递给排序类的某个方法,向排序类中使用campare方法使用的自定义类。

// 1.创建一个实现 Comparator 接口的对象
Comparator comparator = new Comparator() {
    @Override
    public int compare(Object object1, Object object2) {
        if (object1 instanceof NewBookBean && object2 instanceof NewBookBean){
            NewBookBean newBookBean = (NewBookBean) object1;
            NewBookBean newBookBean1 = (NewBookBean) object2;
            //具体比较方法参照 自然排序的 compareTo 方法,这里只举个栗子
            return newBookBean.getCount() - newBookBean1.getCount();
        }
        return 0;
    }
};
 
//2.将此对象作为形参传递给 TreeSet 的构造器中
TreeSet treeSet = new TreeSet(comparator);
 
//3.向 TreeSet 中添加 步骤 1 中 compare 方法中设计的类的对象
treeSet.add(new NewBookBean("A",34));
treeSet.add(new NewBookBean("S",1));
treeSet.add( new NewBookBean("V",46));
treeSet.add( new NewBookBean("Q",26));

总结:

1)java中两种排序方式:

    Comparable实体类实现,自然排序、Comparator定制排序,无法修改实体类时直接在调用方法创建

2)Comparator的使用是一种策略模式

3)对于普通类型String、Integer、Double等已经实现了Comparable接口,可以直接使用

4)对于一些自定义类,在不同情况下需要实现一些不同的比较策略,可以创建Comparator接口实现

猜你喜欢

转载自blog.csdn.net/weixin_40018934/article/details/81071104