TreeSet是一个集合类,用法很普遍,下面一些代码段供大家参考
定义TreeSet对象
TreeSet tset=new TreeSet();
添加数据信息
tset.add(new String("1"));
tset.add(new String("2"));
tset.add(new String("3"));
遍历所有信息:
Iterator it=tset.iterator();
while(it.hasnext()){
System.out.println(it.next());
}
如果我们想要排序,添加tset.comparator()方法即可实现自然排序,但是如果我们希望,我们自己定义进行排序呢?
那就要用到我们自己定义的比较器,需要我们实现Comparator这个接口类
//定义一个比较器
class MyCompare implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
Student upStu1 = (Student)o1;
Student upStu2 = (Student)o2;
int result=0;
if(upStu1.getAge()>upStu2.getAge()){
result=1;
}else if(upStu1.getAge()==upStu2.getAge()){
result=0;
}else{
result=-1;
}
return result;
}
}
一个集合内放入的元素类型类:
定义//定义一个对象
class Student {
private String name;
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;
}
private int age;
Student(String name,int age){
this.name=name;
this.age=age;
}
}
测试主类:
public class TreeSetDemo{
public static void main(String[] args) {
Student s1=new Student("zhangsan",24);
Student s2=new Student("li",23);
MyCompare mc=new MyCompare();
TreeSet tSet = new TreeSet(mc);
tSet.add(s1);
tSet.add(s2);
Iterator it=tSet.iterator();
System.out.println("集合中的所有元素为:"+tSet.size());
while (it.hasNext()) {
//UpdateStu stu=(UpdateStu)it.next();
//System.out.println("学号:"+stu.id+";姓名:"+stu.name);
Student s11=(Student)it.next();
System.out.println(s11.getName()+","+s11.getAge());
}
}
}