关于实现Comparable接口的一个小程序
来源:互联网 发布:cf手游改枪皮肤软件盒 编辑:程序博客网 时间:2024/04/28 00:22
- import java.util.*;
- public class EmployeeSortTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Employee[] staff = new Employee[3];
- staff[0] = new Employee("harry Hacker",35000);
- 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(10000000);
- }
- 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;
- }
转至:http://sevven.javaeye.com/blog/173907
- 关于实现Comparable接口的一个小程序
- Comparable接口的实现
- 原创---关于实现comparable接口的排序例子
- (java)关于List中对象实现Comparable接口的例子
- DelayQueue实现的Comparable接口
- Java的Comparable接口的一个陷阱
- 关于Comparable接口
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的用法和实现
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- Comparable接口的实现和使用
- 计算机专业考研一些参考书籍
- SQL Cookbook
- OpenGL(R) Distilled
- Best of Ruby Quiz
- 对话框中加入标签页的5种方法
- 关于实现Comparable接口的一个小程序
- JUnit in Action
- Windows Graphics Programming: Win32 GDI and DirectDraw
- 20件Win平台不行而Linux能搞定的事情
- Designing Effective Database Systems
- 802.11 WLANs and IP Networking: Security, QoS, and Mobility
- Web ReDesign 2.0: Workflow that Works
- Killer Game Programming in Java
- Wireless Game Development in C/C++ with BREW