标签:
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.List; 4 5 /** 6 * @title 接口继承多态的经典范例 7 * @author 作者:sunshine yaqingl 8 * @date 创建时间:2016年7月6日 下午5:27:39 9 */ 10 11 //使用Comparable接口自定义排序 12 class Employee implements Comparable<Employee>{ 13 private int id; 14 private String name; 15 private int age; 16 public Employee(int id,String name,int age){ 17 this.id=id; 18 this.age=age; 19 this.name=name; 20 } 21 @Override 22 public int compareTo(Employee o){ 23 if(age>o.age){ 24 return 1; 25 }else if(age<o.age){ 26 return -1; 27 } 28 return 0; 29 } 30 @Override 31 public String toString(){ 32 StringBuilder sb=new StringBuilder(); 33 sb.append("员工的编号:"+id+","); 34 sb.append("员工的姓名"+ name+","); 35 sb.append("员工的年龄:"+age); 36 return sb.toString(); 37 } 38 39 } 40 41 public class Hello4IEPExample { 42 43 public static void main(String[] args) { 44 // TODO Auto-generated method stub 45 /**************使用Comparable接口自定义比较**************/ 46 //使用Comparable接口自定义比较 47 Employee employee=new Employee(1,"sunshine",28); 48 Employee employee1=new Employee(2,"habit",26); 49 Employee employee2=new Employee(3,"Liuliu",30); 50 String mm; 51 if (employee.compareTo(employee2) ==1){ 52 mm=employee.toString(); 53 } 54 else{ 55 mm=employee2.toString(); 56 } 57 58 System.out.println(mm); 59 //使用Comparable接口自定义排序 60 List<Employee> list=new ArrayList<Employee>(); //之后了解相关功能 61 list.add(employee); 62 list.add(employee1); 63 list.add(employee2); 64 System.out.println("排序前:"); 65 for(Employee e : list){ 66 System.out.println(e); 67 } 68 69 System.out.println("排序前:"); 70 Collections.sort(list); 71 for(Employee e : list){ 72 System.out.println(e); 73 } 74 75 76 } 77 78 }
标签:
原文地址:http://www.cnblogs.com/sunshine-habit/p/5647815.html