集合框架_TreeSet保证元素唯一性和比较器排序的原理及代码实现
2017-01-07 18:52
501 查看
package cn.itcast_07; import java.util.Comparator; import java.util.TreeSet; /* * 需求:请按照姓名的长度排序 */ public class TreeSetDemo { public static void main(String[] args) { // 创建集合对象 // TreeSet<Student> ts = new TreeSet<Student>();//自然排序 // public TreeSet(Comparator comparator)//比较器排序 // TreeSet<Student> ts = new TreeSet<Student>(new MyComparator()); // 如果一个方法的参数是接口,那么真正要的是该接口的实现类对象 // 而匿名内部类就能实现这个东西 TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() { public int compare(Student s1, Student s2) { // 姓名长度 int num = s1.getName().length() - s2.getName().length(); // 姓名内容 int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num; // 年龄 int num3 = num2 == 0 ? s1.getAge() - s2.getAge() : num2; return num3; } }); // 创建学生对象 Student s1 = new Student("linqingxia", 27); Student s2 = new Student("zhangguorong", 29); Student s3 = new Student("wanglihong", 23); Student s4 = new Student("linqingxia", 27); Student s5 = new Student("liushishi", 22); Student s6 = new Student("wuqilong", 40); Student s7 = new Student("fengqingyang", 22); Student s8 = new Student("linqingxia", 29); // 添加元素 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.getName() + "---" + s.getAge()); } } }
package cn.itcast_07;
public class 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;
}
}
相关文章推荐
- Java基础知识强化之集合框架笔记47:Set集合之TreeSet保证元素唯一性和比较器排序的原理及代码实现(比较器排序)
- 集合框架_TreeSet保证元素唯一性和自然排序的原理和图解(二叉树结构)
- 集合框架-TreeSet保证元素唯一性和自然排序的原理和图解
- Java基础知识强化之集合框架笔记44:Set集合之TreeSet保证元素唯一性和自然排序的原理和图解
- 集合框架_TreeSet保证元素排序的源码解析
- TreeSet保证元素唯一并实现排序的原理
- 集合框架_HashSet保证元素唯一性的代码体现及图解
- TreeSet保证元素的 排序和唯一性 的原理
- TreeSet保证元素唯一并实现排序的原理
- 集合框架_集合嵌套存储和遍历元素的案例图解、集合嵌套存储和遍历元素的案例代码实现
- 集合框架-HashSet存储元素保证唯一性的图解
- 集合框架_HashSet保证元素唯一性的源码解析
- Treeset保证元素唯一且排序的代码示例
- TreeSet集合存放自定义类型的对象,可以使用比较器,实现Comparable接口自己设置排序方式
- 集合框架_TreeSet的add()方法源码再次解读和TreeSet对元素排序的总结
- TreeSet保证元素唯一性原理图解
- 集合框架——TreeSet实现原理及源码分析
- 集合框架_模拟斗地主洗牌和发牌并对牌进行排序的代码实现
- 排序技术_各种算法原理 图解 代码实现
- HashSet集合是如何保证元素的唯一性的?