现在还来得及
—— 24.6.3
一、TreeSet
1.概述:
Treeset是set的实现类
2.特点:
a.对元素进行排序
b.无索引
c.不能存null
d.线程不安全
e.元素唯一3.数据结构:
红黑树
4.构造
Treeset() —> 构造一个新的空 set,该 set 根据其元素的自然顺序进行排序 -> ASCII
Treeset(comparator<? super E> comparator) —> 构造一个新的空 Treeset,它根据指定比较器进行排序public class Person { private String name; private Integer age; public Person() { } public Person(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 "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
import java.util.TreeSet; public class Demo252TreeSet01 { public static void main(String[] args) { TreeSet<String> set1 = new TreeSet<>(); set1.add("c.白毛浮绿水"); set1.add("a.鹅鹅鹅"); set1.add("b.曲项向天歌"); set1.add("d.红掌拨清波"); System.out.println(set1); // [a.鹅鹅鹅, b.曲项向天歌, c.白毛浮绿水, d.红掌拨清波] } }
import java.util.Comparator; import java.util.TreeSet; public class Demo253TreeSet02 { public static void main(String[] args) { TreeSet<Person> treeSet = new TreeSet<>(new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return o1.getAge()-o2.getAge(); } }); treeSet.add(new Person("小明",17)); treeSet.add(new Person("小红",18)); treeSet.add(new Person("小刚",16)); System.out.println(treeSet); // [Person{name='小刚', age=16}, Person{name='小明', age=17}, Person{name='小红', age=18}] } }
二、TreeMap
标签:重学,java,58,age,Person,String,new,public,name From: https://blog.csdn.net/m0_73983707/article/details/1394224971.概述:
Treeset是set的实现类
2.特点:
a.对元素进行排序
b.无索引
c.key唯一
d.线程不安全
e.不能存null3.数据结构:
红黑树
4.构造:
TreeMap() —> 使用键的自然顺序构造一个新的、空的树映射 —> ASCII
TreeMap(Comparator<?super E> comparator) —> 构造一个新的、空的树映射,该映射根据给定比较器进行排序import java.util.Comparator; import java.util.TreeMap; public class Demo254TreeMap01 { public static void main(String[] args) { TreeMap<String, String> map = new TreeMap<>(); map.put("a", "苦难是生活的花开"); map.put("c","一切都会好的"); map.put("b","我一直相信"); System.out.println(map); TreeMap<Person, String> map2 = new TreeMap<>(new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return o1.getAge()-o2.getAge(); } }); map2.put(new Person("小明",17),"北京"); map2.put(new Person("小红",18),"上海"); map2.put(new Person("小刚",16),"江苏"); System.out.println(map2); } }