关于compareTo()的重载 转

import java.util.SortedSet;
import java.util.TreeSet;

public class UserBean implements Comparable<UserBean>{
private String username;
private int age;

public UserBean(String username,int age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}





@Override
public int compareTo(UserBean user) {
int i = 0;
if(user!=null){
i = this.age-user.age;
if(i==0){//如果年龄相同,则比较姓名,否则只能显示一个人
i = this.username.hashCode()-user.username.hashCode();
}
}
return i;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return this.username+":"+this.age;
}

public static void main(String[] args) {
TreeSet sortedSet = new TreeSet();
UserBean userBean1 = new UserBean("lj", 20);
UserBean userBean2 = new UserBean("li", 20);
sortedSet.add(userBean1);
sortedSet.add(userBean2);
System.out.println(sortedSet);

}

}

你可能感兴趣的:(compareTo)