TreeSet:
1.向TreeSet添加元素时
如果元素具有自然特性,那么就按照元素的自然顺序的特点进行排序储存。
如果不具备,就要实现Compareable接口中的compareTo() 方法。
可以直接实现Compareable接口,但最好自己定义比较器类。
2.TreeSet的底层实现是红黑树,也叫二叉树,集合中的元素一个个进行比较时
当把拿出来的第一个元素当成树根,依次拿其它元素进行比较如果大于树根
就放在其右支,小于则放在其左支,如此迭代,直到所有元素被比较完,安放完。
注意:在二叉树中出现3个元素,还未形成二叉结构时,就要重新排列,就是把
根和支的位置改变了。
(1, 2,3,4) (a, b, c, d )自然顺序
import java.util.*; import java.util.ListIterator; public class ex12 { public static void main(String[] args) { TreeSet set = new TreeSet(); set.add(new Emp(100, "Tom", 100)); set.add(new Emp(101, "Tom", 400)); set.add(new Emp(109, "Tom", 100));//Ctrl + d set.add(new Emp(109, "Tom", 99));//Ctrl + d set.add(new Emp(209, "Tom", 130));//Ctrl + d System.out.println(set); } } class Emp implements Comparable{ int id; String name; int money; public Emp(int id, String name, int money) { this.id = id; this.name = name; this.money = money; } @Override public String toString() { return "{ id = " + this.id + " ,name = " + this.name + " ,money = " + money + " }"; } @Override//Ctrl + O public int compareTo(Object o) { Emp e = (Emp)o; return this.money - e.money ; } }
[{ id = 109 ,name = Tom ,money = 99 }, { id = 100 ,name = Tom ,money = 100 }, { id = 209 ,name = Tom ,money = 130 }, { id = 101 ,name = Tom ,money = 400 }] Process finished with exit code 0
import java.util.*; import java.util.ListIterator; public class ex12 { public static void main(String[] args) { MyCompare my = new MyCompare(); TreeSet set = new TreeSet(my);//创建构造器时传入构造器*********** set.add(new Emp(100, "Tom", 100)); set.add(new Emp(101, "Tom", 400)); set.add(new Emp(109, "Tom", 100));//Ctrl + d set.add(new Emp(109, "Tom", 99)); set.add(new Emp(209, "Tom", 130)); System.out.println(set); } } class Emp { int id; String name; int money; public Emp(int id, String name, int money) { this.id = id; this.name = name; this.money = money; } @Override public String toString() { return "{ id = " + this.id + " ,name = " + this.name + " ,money = " + money + " }"; } } //自定义构造器 class MyCompare implements Comparator<Emp> { @Override public int compare(Emp o1, Emp o2) { return o1.id - o2.id; } }//按id排序
[{ id = 100 ,name = Tom ,money = 100 }, { id = 101 ,name = Tom ,money = 400 }, { id = 109 ,name = Tom ,money = 100 }, { id = 209 ,name = Tom ,money = 130 }] Process finished with exit code 0
时间: 2024-10-26 16:01:44