关于实现Comparable接口的一个小程序

来源:互联网 发布:cf手游改枪皮肤软件盒 编辑:程序博客网 时间:2024/04/28 00:22
  1. import java.util.*;   
  2. public class EmployeeSortTest {   
  3.   
  4.     /**  
  5.      * @param args  
  6.      */  
  7.     public static void main(String[] args) {   
  8.         // TODO Auto-generated method stub   
  9.         Employee[] staff = new Employee[3];   
  10.         staff[0] = new Employee("harry Hacker",35000);   
  11.         staff[1] = new Employee("carl cracke",75000);   
  12.         staff[2] = new Employee("tony Tester",38000);   
  13.            
  14.         Arrays.sort(staff);//sort方法可以实现对对象数组排序,但是必须实现                 Comparable接口   
  15.                            /*Comparable接口原型为:  
  16.                             * public interface Comparable<T>  
  17.                             * {  
  18.                             *      int compareTo(T other);//接口的中方法自动属于public方法  
  19.                             * }  
  20.                             */  
  21.         for(Employee e: staff)   
  22.             System.out.println("id="+e.getId()+"  name="+e.getName()+   
  23.                     ".salary="+e.getSalary());   
  24.     }   
  25.   
  26. }   
  27. /*  
  28.  * 因为要实现对Employee对象的排序,所以在Employee类中要实现Comparable接口,  
  29.  * 也就是要实现comepareTo()方法  
  30.  */  
  31. class Employee implements Comparable<Employee>   
  32. {   
  33.     public Employee(String n,double s)   
  34.     {   
  35.         name = n;   
  36.         salary = s;   
  37.         Random ID = new Random();   
  38.         id = ID.nextInt(10000000);   
  39.     }   
  40.     public int getId()   
  41.     {   
  42.         return id;   
  43.     }   
  44.     public String getName()   
  45.     {   
  46.         return name;   
  47.     }   
  48.        
  49.     public double getSalary()   
  50.     {   
  51.         return salary;   
  52.     }   
  53.        
  54.     public void raiseSalary(double byPercent)   
  55.     {   
  56.         double raise  = salary *byPercent/100;   
  57.         salary+=raise;   
  58.     }   
  59.        
  60.     public int compareTo(Employee other)   
  61.     {   
  62.         if(id<other.id)//这里比较的是什么 sort方法实现的就是按照此比较的东西从小到大排列   
  63.             return -1;   
  64.         if(id>other.id)   
  65.             return 1;   
  66.         return 0;   
  67.     }   
  68.     private int id;   
  69.     private String name;   
  70.     private double salary;   
  71. }  

转至:http://sevven.javaeye.com/blog/173907