Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4536577
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Java

2012-03-24 19:56:14

来源:

List of objects that implement this interface can be sorted automatically by sort method of the list interface. This interface has compareTo() method that is used by the sort() method of the list.

In this code Employee class is implementing Comparable interface and have method compareTO(). ComparableDemo.java is showing the use of this interface. This class first makes a list of objects of type Employee and call sort method of java.util.Collections, which internally uses compareTo() method of Employee class and sort the list accordingly.

Employee.java

public class Employee implements Comparable {

    int EmpID;
    String Ename;
    double Sal;
    static int i;

    public Employee() {
        EmpID = i++;
        Ename = "dont know";
        Sal = 0.0;
    }

    public Employee(String ename, double sal) {
        EmpID = i++;
        Ename = ename;
        Sal = sal;
    }

    public String toString() {
        return "EmpID " + EmpID + "\n" "Ename " + Ename + "\n" "Sal" + Sal;
    }

    public int compareTo(Object o1) {
        if (this.Sal == ((Employeeo1).Sal)
            return 0;
        else if ((this.Sal((Employeeo1).Sal)
            return 1;
        else
            return -1;
    }
}

ComparableDemo.java

import java.util.*;

public class ComparableDemo{

    public static void main(String[] args) {

        List ts1 = new ArrayList();
        ts1.add(new Employee ("Tom",40000.00));
        ts1.add(new Employee ("Harry",20000.00));
        ts1.add(new Employee ("Maggie",50000.00));
        ts1.add(new Employee ("Chris",70000.00));
        Collections.sort(ts1);
        Iterator itr = ts1.iterator();

        while(itr.hasNext()){
            Object element = itr.next();
            .out.println(element + "\n");
            
        }

    }
}

Output:

EmpID 1 Ename Harry Sal20000.0 EmpID 0 Ename Tom Sal40000.0 EmpID 2 Ename Maggie Sal50000.0 EmpID 3 Ename Chris Sal70000.0
阅读(794) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~