您的位置:首页 > 其它

TreeSet存储自定义对象并保证排序和唯一

2016-04-19 12:57 555 查看
TreeSet存储自定义对象并保证排序和唯一

/*
如果一个类的元素要想能够进行自然排序,就必须实现自然排序接口
*/
public
class
Student implementsComparable<Student>{

private String
name;
private
int
age;

public Student() {
super();
// TODO Auto-generated constructor stub
}

public Student(String name,
int age) {
super();
this.name = name;
this.age = age;
}

public String getName() {
return
name;
}
public
void
setName(String name) {
this.name = name;
}
public
int
getAge() {
return
age;
}
public
void
setAge(int age) {
this.age = age;
}

@Override
public
int
compareTo(Student s) {
// TODO Auto-generated method stub
// return-1;
//这里返回什么,其实应该根据我的排序规则来做
//按照年龄排序,主要条件
int num =
this.age - s.age;
//次要条件
//年龄相同的时候,还的看姓名是否也相同
//如果年龄和姓名都相同,才是同一个元素
int
num2 = num ==0 ? this.name.compareTo(s.name) : num;
return
num2;
}

}

import java.util.TreeSet;

/*
TreeSet存储自定义对象并保证排序和唯一
A:你没有告诉我们怎样排序
自然排序,按照从小到大
B:元素什么情况算唯一你也没有告诉我
成员变量都相同即为同一个元素
*/
public
class
TreeSetDemo2 {

public
static void
main(String[] args) {
// TODO Auto-generated method stub

//创建集合对象
TreeSet<Student>ts = newTreeSet<Student>();

//创建元素
Students1 = newStudent("linqingxia",27);
Students2 = newStudent("linqingxia2",28);
Students3 = newStudent("linqingxia3",29);
Students4 = newStudent("linqingxia4",26);
Students5 = newStudent("linqingxia5",25);
Students6 = newStudent("linqingxia",27);
Students7 =
new
Student("linqingxia46",26);

//天假元素
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
ts.add(s7);

//遍历
for(Student s : ts){
System.out.println(s.getName()+"---"+s.getAge());
}
}

}

运行结果:

linqingxia5---25
linqingxia4---26
linqingxia46---26
linqingxia---27
linqingxia2---28
linqingxia3---29
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: