zoukankan      html  css  js  c++  java
  • How to use Comparable Interface

    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.

    If you defined Comparable<T>, you need to use Employee e in function ‘publicint compareTo(Employee e) {‘ argument.

     

    package algorithms;

    publicclass Employee implements Comparable<Employee>{

        intEmpID;

        String Ename;

        doubleSalary;

        staticinti;

       

        public Employee(String ename,double salary){

          EmpID=i++;

          Ename=ename;

          Salary=salary;

        }

       

        public String toString(){

          return"EmpID:" +EmpID+"\n"+"Ename:"+Ename+"\n"+"Salary:"+Salary;

        }

          @Override

          publicint compareTo(Employee e) {

                // TODO Auto-generated method stub

                if(this.Salary==((Employee)e).Salary){

                      return 0;

                }elseif((this.Salary)>((Employee)e).Salary){

                      return 1;

                }else{

                      return -1;

                }

          }

    }

    package algorithms;

    import java.util.*;

    publicclass EmployeeDemo {

         publicstaticvoid 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()){

                 Employee element=(Employee)itr.next();

                 System.out.println(element+"\n");

             }

         }

    }

     

    Output:

    EmpID:1

    Ename:Harry

    Salary:20000.0

    EmpID:0

    Ename:Tom

    Salary:40000.0

    EmpID:2

    Ename:Maggie

    Salary:50000.0

    EmpID:3

    Ename:Chris

    Salary:70000.0

  • 相关阅读:
    设计模式(十五)---桥梁模式
    设计模式(十四)---门面模式
    设计模式(十三)---享元模式
    设计模式(十二)---代理模式
    设计模式(十一)---装饰者模式
    设计模式(十)---合成模式
    设计模式(九)---缺省适配器模式
    设计模式(八)---适配器模式
    设计模式(七)---原始模型模式
    一张图看懂JavaScript中数组的迭代方法:forEach、map、filter、reduce、every、some
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3132334.html
Copyright © 2011-2022 走看看