首页 > 代码库 > Java实例对象间的比较(实现Comparable接口)
Java实例对象间的比较(实现Comparable接口)
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));
}
}
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);
}
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);
}
Java实例对象间的比较(实现Comparable接口)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。