码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-09-22 23:21:13      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:io   os   java   ar   for   div   sp   cti   on   

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接口)

标签:io   os   java   ar   for   div   sp   cti   on   

原文地址:http://www.cnblogs.com/oraclespace/p/3986655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!