首页 > 代码库 > 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));
 }
 
}
 
 
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);
 }
 

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