您的位置:首页 > 编程语言 > Java开发

Java实例对象间的比较(实现Comparable接口)

2014-09-22 20:15 676 查看
int compareTo(T o)

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

class Name implements Comparable{
private String firstName,lastName;
public Name(String firstName,String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

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

public boolean equals(Object obj){
if(obj instanceof Name){
Name name = (Name)obj;
return (firstName.equals(name.firstName)&&
lastName.equals(name.lastName));
}
return super.equals(obj);
}
@Override
public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp!=0 ? lastCmp:firstName.compareTo(n.firstName));
}

}

public static void main(String[] args) {
List ll = new LinkedList();
ll.add(new Name("Karl","M"));
ll.add(new Name("Steven","Lee"));
ll.add(new Name("John","o"));
ll.add(new Name("Tom","M"));
System.out.println(ll);
Collections.sort(ll);
System.out.println(ll);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: