zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    通过具名 slot (插槽)来显示Dialog 的标题
    elementUI 中,table表格如何实现当某一行被点击时会触发该事件(row-click)
    switch循环
    CSS动画
    for循环
    Display
    修改页面标题前的图标
    from表单
    CSS3文字效果
    CSS颜色渐变
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13447113.html
Copyright © 2011-2022 走看看