一.简介
TreeSet是以红黑树的结构存储数据的集合,它能对数据作出顺序排序
二.TreeSet的方法
TreeSet<String> treeSet = new TreeSet<String>();
treeSet.add("haha");
treeSet.add("love");
treeSet.add("me");
treeSet.add("nihao");
treeSet.add("yes");
treeSet.add("you");
String first = treeSet.first();//第一个元素
String last = treeSet.last();//最后一个元素
String lower = treeSet.lower("you");//比"you"小的前一个元素
String highter = treeSet.higher("you");//比"you"大的后一个元素
SortedSet<String> subSet = treeSet.subSet("haha", "me");//子集,包括"haha",不包括"me"
SortedSet<String> headSet = treeSet.headSet("you");//比"you"小的所有元素集合
SortedSet<String> tailSet = treeSet.tailSet("love");//比"you"大或者等于的所有元素集合
Log.d(TAG, "testDemo: first = " + first);
Log.d(TAG, "testDemo: last = " + last);
Log.d(TAG, "testDemo: lower = " + lower);
Log.d(TAG, "testDemo: highter = " + highter);
Log.d(TAG, "testDemo: subSet = " + subSet.toString());
Log.d(TAG, "testDemo: headSet = " + headSet.toString());
Log.d(TAG, "testDemo: tailSet = " + tailSet.toString());
输出结果是
2019-08-02 17:01:17.717 24932-24948/com.hezhong.demolauncherservice D/ExampleInstrumentedTest: testDemo: first = haha
2019-08-02 17:01:17.717 24932-24948/com.hezhong.demolauncherservice D/ExampleInstrumentedTest: testDemo: last = you
2019-08-02 17:01:17.717 24932-24948/com.hezhong.demolauncherservice D/ExampleInstrumentedTest: testDemo: lower = yes
2019-08-02 17:01:17.717 24932-24948/com.hezhong.demolauncherservice D/ExampleInstrumentedTest: testDemo: highter = null
2019-08-02 17:01:17.717 24932-24948/com.hezhong.demolauncherservice D/ExampleInstrumentedTest: testDemo: subSet = [haha, love]
2019-08-02 17:01:17.717 24932-24948/com.hezhong.demolauncherservice D/ExampleInstrumentedTest: testDemo: headSet = [haha, love, me, nihao, yes]
2019-08-02 17:01:17.718 24932-24948/com.hezhong.demolauncherservice D/ExampleInstrumentedTest: testDemo: tailSet = [love, me, nihao, yes, you]
三.实现Comparable接口
class Fruit implements Comparable {
String name;
int count;
@Override
public int compareTo(Object o) {
Fruit f = (Fruit) o;
if (this.count == f.count) {
return 0;
} else if (this.count > f.count) {
return 1;
}
return -1;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
Fruit f = (Fruit) obj;
if (this.count == f.count) {
return true;
}
}
return false;
}
}
四.定制接口,实现Comparator
TreeSet<AllApp> treeSet = new TreeSet<AllApp>(new Comparator<AllApp>() {
@Override
public int compare(AllApp o1, AllApp o2) {
if (o1.packageName.equals(o2.packageName) && o1.systemApp == o2.systemApp) {
return 0;
}
if (o1.packageName.hashCode() > o2.packageName.hashCode()) {
return 1;
}
return -1;
}
});