【2022-05-06】基因的祕密
阿新 • • 發佈:2022-05-10
TreeSet
概述
TreeSet是一種有序,無腳標,不可重複的集合
底層是紅黑樹,是一種平衡二叉樹
TreeSet對集合中元素如果是自定義類,實現排序有兩種方法
1.自定義類繼承Comparable介面
2.TreeSet構造方法引數中建立Comparator的匿名類
實現Comparable介面
package com.qianfeng.collection; import java.util.Iterator; import java.util.TreeSet; /** * 功能描述 * * @since 2022-05-13 */ public class TreeSetDemo { public static void main(String[] args) { TreeSet<Person1> treeSet = new TreeSet(); Person1 person = new Person1("zhangsan", 1); Person1 person1 = new Person1("lisi", 2); Person1 person2 = new Person1("wangwu", 3); treeSet.add(person); treeSet.add(person1); treeSet.add(person2); System.out.println(treeSet); treeSet.remove(new Person1("wangwu", 3)); Iterator<Person1> iterator = treeSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next().getName()); } System.out.println(treeSet.isEmpty()); System.out.println(treeSet.contains(new Person1("lisi", 2))); } } class Person1 implements Comparable<Person1> { private String name; private Integer age; public Person1(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Preson{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Person1 o) { int n1 = name.compareTo(o.name); int n2 = age - o.age; return n1 == 0 ? n2 : n1; } }
構造Comparator匿名內部類
package com.qianfeng.collection; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; /** * 功能描述 * * @since 2022-05-13 */ public class TreeSetDemo2 { public static void main(String[] args) { TreeSet<Person1> person1s = new TreeSet<>(new Comparator<Person1>() { @Override public int compare(Person1 o1, Person1 o2) { int n1 = o1.getAge() - o2.getAge(); int n2 = o1.getName().compareTo(o2.getName()); return n1 == 0 ? n2 : n1; } }); Person1 person = new Person1("zhangsan", 1); Person1 person1 = new Person1("lisi", 2); Person1 person2 = new Person1("wangwu", 3); person1s.add(person); person1s.add(person1); person1s.add(person2); System.out.println(person1s); person1s.remove(new Person1("zhangsan", 1)); Iterator<Person1> it = person1s.iterator(); while (it.hasNext()) { System.out.println(it.next().getName()); } System.out.println(person1s.isEmpty()); person1s.contains(new Person1("wangwu", 3)); } }