TreeSet:让Set无序的特性变为有序
Set:无序,不可以重复元素
- HashSet:数据结构是哈希表,线程是非同步的。保证元素唯一性的原理:判断元素的hashCode值是否相同。如果相同,还会继续判断元素的equals方法是否为true。
- TreeSet:可以对Set集合中的元素进行排序。
TreeSet
自带排序的字典,使用方法与HashSet一致。默认是根据字母大小排序,可自定义排序规则
示例:
TreeSet ts = new TreeSet();
ts.add("ccss");
ts.add("asdf");
ts.add("fgd");
ts.add("awd");
Iterator it = ts.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
输出:
asdf
awd
ccss
fgd
TreeSet排序的第一种方式:让元素自身具备比较性。
元素需要实现Comparable接口,覆盖compareTo方法。
这种方式也称为元素的自然排序,或者叫默认排序
TreeSet排序的第二种方式:当元素自身不具备比较性时,或者具备的比较性不是所需要的。这时就需要让集合自身具备比较性。
在集合初始化时,就有了比较方式。
需求:
往TreeSet集合中存储自定义对象学生。
想按照学生的年龄进行排序。
第一种表示方式:
学生对象类Student里实现Comparable,并复写compareTo方法:
import java.util.*;
public class test{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("ccss", 12));
ts.add(new Student("ad", 15));
ts.add(new Student("tss", 16));
ts.add(new Student("yy", 8));
Iterator it = ts.iterator();
while (it.hasNext()){
Student out = (Student) it.next();
System.out.println(out.getAge() + "..." + out.getName());;
}
}
}
class Student implements Comparable{
private String name;
private int age;
public Student(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public int compareTo(Object o) {
if(!(o instanceof Student))
throw new RuntimeException("不是学生对象");
Student s = (Student)o;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return this.name.compareTo(s.name); // 当年龄相等的时候再按照名字排序
return -1; // 仅当this.age<s.age时返回-1
}
}
第二种表示方式
新建一个比较类,继承Comparator
(为了观察直观,只写出核心代码):
class MyCompare implements Comparator
{
@Override
public int compare(Object o1, Object o2) {
return 0; // 这里的返回值决定了排序
}
}
// 在声明TreeSet时,添加比较器进去。
TreeSet ts = new TreeSet(new MyCompare());
第三种表示方式:
在声明TreeSet里直接new一个比较器
TreeSet ts = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return 0;
}
});
// 在声明TreeSet时,添加比较器进去。
TreeSet ts = new TreeSet(new MyCompare());