集册 Java实例教程 Java Collection实现通用Comparable接口

Java Collection实现通用Comparable接口

欢马劈雪     最近更新时间:2020-01-02 10:19:05

522
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
Java集合实现通用可比较接口
//来 自 nowjava.com - 时代Java

import java.util.*;

import java.util.*;


public class NameSort {

    public static void main(String[] args) {

        Name nameArray[] = { new Name("John", "Smith"),

                new Name("Karl", "Ng"), new Name("Jeff", "Smith"),

                new Name("Tom", "Rich") };


        List<Name> names = Arrays.asList(nameArray);

        Collections.sort(names);

        System.out.println(names);

    }

}

class Name implements Comparable<Name> {

    private final String firstName, lastName;


    public Name(String firstName, String lastName) {

        if (firstName == null || lastName == null)

            throw new NullPointerException();

        this.firstName = firstName;

        this.lastName = lastName;/* 来自 nowjava - 时代Java*/

    }


    public String firstName() {

        return firstName;

    }


    public String lastName() {

        return lastName;

    }


    public boolean equals(Object o) {

        if (!(o instanceof Name))

            return false;

        Name n = (Name) o;

        return n.firstName.equals(firstName) && n.lastName.equals(lastName);

    }


    public int hashCode() {

        return 31 * firstName.hashCode() + lastName.hashCode();

    }


    public String toString() {

        return firstName + " " + lastName;

    }


    public int compareTo(Name n) {

        int lastCmp = lastName.compareTo(n.lastName);

        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));

    }

}


展开阅读全文