a- package treesetdemo;
- import java.util.Comparator;
- import java.util.TreeSet;
- public class TreeSetDemo1 {
- /**
- * 需求:存储自定义的学生对象,并保证元素的唯一性,并按照名字长度排序
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //建立TreeSet
-
- // TreeSet<Student> ts = new TreeSet<Student>();//无参构造函数 自然排序
- // TreeSet<Student> ts = new TreeSet<Student>(new MyComparator());//自定义比较器
-
- //单次使用的参数为引用对象变量时,可使用匿名内部类
- TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){
- public int compare( Student s1, Student s2) {
- // TODO Auto-generated method stub
- //按姓名长度排序
- int num = s1.getName().length() - s2.getName().length();
- if(num==0) //长度相同则比较姓名顺序
- num = s1.getName().compareTo(s2.getName());
- if(num == 0)//姓名相同则比价年龄
- num = s1.getAge() - s2.getAge();
- return num;
- }
- });
- //建立学生对象
- Student s1 = new Student("uiui",18);
- Student s2 = new Student("hahah",22);
- Student s3 = new Student("gege",12);
- Student s4 = new Student("Liliddd",18);
- Student s5 = new Student("Licu",13);
- Student s6 = new Student("Li",18);
- //添加对象
- ts.add(s1);
- ts.add(s2);
- ts.add(s3);
- ts.add(s4);
- ts.add(s5);
- ts.add(s6);
- //遍历集合
- for(Student s: ts){
- System.out.println(s.getName()+"..."+s.getAge());
- }
- }
- }
复制代码
|
|