为了练习Comparable接口,实现其compareTo方法,从而为英文姓名进行排序
这里一个姓名类,有成员变量firstName和lastName,都是String类型。这个姓名类需要实现Comparable接口,从而实现排序。
附代码:
package compare; //英文姓名排序、通过实现Comparable接口实现compareTo方法来对饮用对象排序 import java.util.*; public class TestSort { public static void main(String[] args) { List<Name> list = new ArrayList<Name>(); list.add(new Name("j","J")); list.add(new Name("d","D")); list.add(new Name("b","B")); list.add(new Name("c","A")); list.add(new Name("a","A")); list.add(new Name("i","I")); list.add(new Name("f","F")); list.add(new Name("g","G")); list.add(new Name("h","G")); System.out.print(list); Collections.sort(list); System.out.println(); System.out.print(list); } } class Name implements Comparable<Name> { private String firstName; private String lastName; Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[").append(this.lastName).append(" ").append(this.firstName).append("]"); return sb.toString(); } public int compareTo(Name n) { // 如果lastName不一样,比较当前对象和传进来对象的lastName的各个字母 // 如果lastName一样,那么比较firstName // 如果lastName和firstName都 一样,表示名字一样,返回0 if(lastName.compareTo(n.lastName) > 0) { return 1; } else if(lastName.compareTo(n.lastName) < 0) { return -1; }else { return firstName.compareTo(n.firstName); } } }
运行结果图:
注:第一行是未排序前,第二行是排序后。