java 接口sort comparable

简介

java 没有对于多继承的实现,为了间接实现多继承,采用了接口的概念

code

package cn;

import java.util.Arrays;

public class EmployeeSortTest {
	public static void main(String[] args) {
		Employee[] staff = new Employee[3];
		
		staff[0] = new Employee("Harry Hacker", 35000);
		staff[1] = new Employee("Carl Cracker", 75000);
		staff[2] = new Employee("Tony Tester", 38000);
		
		Arrays.sort(staff);
		for(Employee e : staff) {
			System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
		}
	}
}

package cn;

public class Employee implements Comparable<Employee> {
	private String name;
	private double salary;
	
	public Employee(String name, double salary) {
		this.name = name;
		this.salary = salary;
	}
	
	public String getName(){
		return name;
	}

	public double getSalary() {
		return salary;
	}
	
	public void raiseSalary(double byPercent) {
		double raise = salary * byPercent / 100;
		salary += raise;
	}
	
	@Override
	public int compareTo(Employee other) {
		// TODO Auto-generated method stub
		return Double.compare(salary,  other.salary);
	}
}

answer

实现了对于员工按照薪水的排序

name=Harry Hacker,salary=35000.0
name=Tony Tester,salary=38000.0
name=Carl Cracker,salary=75000.0
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/13447113.html