Java-TreeSet的用法-入门

时间:2021-02-18 21:30:53

Java语言中,Set接口有3种通用实现:HashSetTreeSet,LinkedHashSet。TreeSet是一种能够对内部元素进行排序的集合,它使用红黑树来存储内部元素,基于元素的值进行排序,它比HashSet要慢。

TreeSet要求内部元素实现Comparable接口,因为它是根据元素的compareTo来排序的。下面是一个demo:

package Colloections;

import java.util.LinkedList;
import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) {
// TODO Auto-generated method stub TreeSet<Person> treeSet = new TreeSet<Person>();
treeSet.add(new Person("albert", 8));
treeSet.add(new Person("bob", 5));
treeSet.add(new Person("bob", 13)); for (Person person : treeSet) {
System.out.printf(person.toString());
}
}
} class Person implements Comparable<Person>{ public String name;
public int age; public Person(String n, int a){
name = n;
age = a;
} public String toString() {
return String.format("Name is %s, Age is %d%n", name, age);
} @Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
int nameComp = this.name.compareTo(o.name);
return (nameComp != 0 ? nameComp : (this.age - o.age));
} }

程序输出为:

Name is albert, Age is 8
Name is bob, Age is 5
Name is bob, Age is 13