使用通用的比较接口 : 泛型集合 « 泛型 « Java 教程

En
Java 教程
1. 语言基础
2. 数据类型
3. 操作符
4. 流程控制
5. 类定义
6. 开发相关
7. 反射
8. 正则表达式
9. 集合
10. 线
11. 文件
12. 泛型
13. 本土化
14. Swing
15. Swing事件
16. 二维图形
17. SWT
18. SWT 二维图形
19. 网络
20. 数据库
21. Hibernate
22. JPA
23. JSP
24. JSTL
25. Servlet
26. Web服务SOA
27. EJB3
28. Spring
29. PDF
30. 电子邮件
31. 基于J2ME
32. J2EE应用
33. XML
34. 设计模式
35. 日志
36. 安全
37. Apache工具
38. 蚂蚁编译
39. JUnit单元测试
Java
Java 教程 » 泛型 » 泛型集合 
12. 2. 3. 使用通用的比较接口
import java.util.Arrays;

class Person implements Comparable<Person> {
  public Person(String firstName, String surname) {
    this.firstName = firstName;
    this.surname = surname;
  }

  public String toString() {
    return firstName + " " + surname;
  }

  public int compareTo(Person person) {
    int result = surname.compareTo(person.surname);
    return result == ? firstName.compareTo(((Personperson).firstName: result;
  }

  private String firstName;

  private String surname;
}

public class MainClass {
  public static void main(String[] args) {
    Person[] authors = 
        new Person("D""S")
        new Person("J""G"),
        new Person("T""C")
        new Person("C""S"),
        new Person("P""C")
        new Person("B""B") };

    Arrays.sort(authors)// Sort using Comparable method

    System.out.println("\nOrder after sorting into ascending sequence:");
    for (Person author : authors) {
      System.out.println(author);
    }

    Person[] people = 
        new Person("C""S")
        new Person("N""K"),
        new Person("T""C")
        new Person("C""D") };
    int index = 0;
    System.out.println("\nIn search of authors:");
    
    for (Person person : people) {
      index = Arrays.binarySearch(authors, person);
      if (index >= 0) {
        System.out.println(person + " was found at index position " + index);
      else {
        System.out.println(person + "was not found. Return value is " + index);
      }
    }
  }
}
Order after sorting into ascending sequence:
  B B
  P C
  T C
  J G
  C S
  D S

  In search of authors:
  C S was found at index position 4
  N Kwas not found. Return value is -5
  T C was found at index position 2
  C Dwas not found. Return value is -4
12. 2. 泛型集合
12. 2. 1. 泛型和集合ArrayList
12. 2. 2. 数组:存储数组中对象类数据项目
12. 2. 3. 使用通用的比较接口
12. 2. 4. 泛型先进先出
12. 2. 5. A list declared to hold objects of a type T can also hold objects that extend from T.
12. 2. 6. 泛型ArrayList工具
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.