zoukankan      html  css  js  c++  java
  • 029_排序

    同java一样:

    在为对象数组进行排序时,比较器的作用非常明显,首先来讲解Comparable接口。

    让需要进行排序的对象实现Comparable接口,重写其中的compareTo(T o)方法

    The implementation of this method should return the following values:
    -    0 if this instance and objectToCompareTo are equal
    -    > 0 if this instance is greater than objectToCompareTo
    -    < 0 if this instance is less than objectToCompareTo

    看例子,这是Comparable接口的示例实现。

    global class Employee implements Comparable {
    public Long id;
    public String name;
    public String phone;
    // Constructor
    public Employee(Long i, String n, String p) {
    id = i;
    name = n;
    phone = p;
    }
    // Implement the compareTo() method
    global Integer compareTo(Object compareTo) {
    Employee compareToEmp = (Employee)compareTo;
    if (id == compareToEmp.id) return 0;
    if (id > compareToEmp.id) return 1;
    return -1;
    }
    }
    

     测试代码:

    List<Employee> empList = new List<Employee>();
    empList.add(new Employee(101,'Joe Smith', '4155551212'));
    empList.add(new Employee(101,'J. Smith', '4155551212'));
    empList.add(new Employee(25,'Caragh Smith', '4155551000'));
    empList.add(new Employee(105,'Mario Ruiz', '4155551099'));
    // Sort using the custom compareTo() method
    empList.sort();
    // Write list contents to the debug log
    System.debug(empList);
    // Verify list sort order.
    System.assertEquals('Caragh Smith', empList[0].Name);
    System.assertEquals('Joe Smith', empList[1].Name);
    System.assertEquals('J. Smith', empList[2].Name);
    System.assertEquals('Mario Ruiz', empList[3].Name);
    此刻,静下心来学习
  • 相关阅读:
    优秀的 Java 项目,代码都是如何分层的?
    计算机应届生月薪大多是多少?
    零基础要怎么学JAVA?
    自学 Java 怎么入门?
    Java学习路线总结,已Get腾讯Offer
    java培训出来的如何找工作?
    离散数学学习笔记
    一些公式
    一个模拟
    秦皇岛wannafly[数论]学习笔记
  • 原文地址:https://www.cnblogs.com/bandariFang/p/7094263.html
Copyright © 2011-2022 走看看