网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 生活知识 知识问答

java中的Set集合TreeSet集合

时间:2026-02-15 15:54:08

1、自然排序:

/*

 * 需求:自定义对象自然排序(按年龄从小到大)且对象唯一!

 * */

public class TreeSetTest {

public static void main(String[] args) {

TreeSet<Student> ts = new TreeSet<Student>();

Student s1 = new Student("one",1);

Student s2 = new Student("two",2);

Student s3 = new Student("three",3);

Student s4 = new Student("four",4);

Student s5 = new Student("five",5);

Student s6 = new Student("six",6);

Student s7 = new Student("six",6);

Student s8 = new Student("four",4);

ts.add(s1);

ts.add(s2);

ts.add(s3);

ts.add(s4);

ts.add(s5);

ts.add(s6);

ts.add(s7);

ts.add(s8);

for(Student s :ts)

{

System.out.println(s.getAge() + s.getName());

}

}

}

2、因为底层是用了comparable的comparetor方法!所以学生类要实现comparable并重写comparable方法:

public class Student implements Comparable<Student>

public int compareTo(Student o) {

//按年龄进行排序:

int num = this.age - o.age;

//去掉重复!

if(num == 0)

{

this.name.compareTo(o.name);

}

return num;

}

3、控制台打印结果:

1one

2two

3three

4four

5five

6six

4、比较器排序:

public class CompareDemo {

public static void main(String[] args) {

TreeSet<Student> ts = new TreeSet<Student>(

//这里用匿名内部类:内部类的格式是new 一个类或者接口然后重写方法就好了!

new Comparator<Student>() {

public int compare(Student o1, Student o2) {

int num = o1.getAge() - o2.getAge();

if(num == 0)

{

o1.getName().compareTo(o2.getName());

}

return num;

};

}

);

Student s1 = new Student("one",1);

Student s2 = new Student("two",2);

Student s3 = new Student("three",3);

Student s4 = new Student("four",4);

Student s5 = new Student("five",5);

Student s6 = new Student("six",6);

Student s7 = new Student("six",6);

Student s8 = new Student("four",4);

ts.add(s1);

ts.add(s2);

ts.add(s3);

ts.add(s4);

ts.add(s5);

ts.add(s6);

ts.add(s7);

ts.add(s8);

for(Student s :ts)

{

System.out.println(s.getAge() + s.getName());

}

}

}

© 2026 阿力知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com