会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
spring3
博客园
首页
新随笔
联系
订阅
管理
java例程练习(Comparable接口)
import java.lang.Comparable; import java.util.List; import java.util.LinkedList; import java.util.Collections; public class TestCompareTo { public static void main(String[] args) { List l1 = new LinkedList(); l1.add(new Name("Karl", "M")); l1.add(new Name("Stever", "Lee")); l1.add(new Name("John", "O")); l1.add(new Name("Tom", "M")); System.out.println(l1); Collections.sort(l1); System.out.println(l1); } } class Name implements Comparable{ private String firstName; private String lastName; Name(String firstName, String lastName) { this.setFirstName(firstName); this.setLastName(lastName); } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } 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); } public int hashCode() { return firstName.hashCode(); } public int compareTo(Object o) { Name n = (Name) o; int lastCmp = lastName.compareTo(n.lastName); return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName)); } }
posted @
2012-05-01 13:40
spring3
阅读(
208
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告