java集合TreeSet实例



java集合TreeSet实例介绍。TreeSet是一个有序集合,TreeSet中的元素将按照升序排列,缺省是按照自然排序进行排列,意味着TreeSet中的元素要实现Comparable接口。或者有一个自定义的比较器。可以在构造TreeSet对象时,传递实现Comparator接口的比较器对象。

<pre code_snippet_id=”262797″ snippet_file_name=”blog_20140328_1_1053524″ name=”code” class=”java”>/*
* Set:无序,不可以重复元素
* |–HashSet:数据结构是哈希表。线程是非同步的
* 保证元素唯一性的原理:判断元素的hashCode值是否相同。
* 如果相同,会继续判断元素的equals方法是否为true。
* |–TreeSet:可以对Set集合中的元素进行排序
* 底层数据结构是二叉树
* 保证元素唯一性的依据是: compareTo方法return的值。 正数,大,0,等,负数,小
*
* TreeSet排序的第一种方式:让元素自身具备比较性。
* 元素需要实现Comparable的接口,覆盖compareTo方法。
* 这种方式也称为元素的自然排序,或者叫做默认顺序。
*
*
*
*
* 需求:
* 往 TreeSet集合中存储自定义对象学生,
* 然后按照学生的年龄进行排序
*
* 记住,排序时,当主要条件相同时,一定要判断次要条件
*/
package test.itheima;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetDemo {

/**
* @param args
*/
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>();

ts.add(new Student(“lisi22″, 22));
ts.add(new Student(“lisi20″, 20));
ts.add(new Student(“lisi40″, 40));
ts.add(new Student(“lisi30″, 30));
ts.add(new Student(“lisi36″, 36));
ts.add(new Student(“lisi90″, 90));
ts.add(new Student(“lisi50″, 50));

Iterator it = ts.iterator();

while (it.hasNext()) {
Student stu = (Student) it.next();
System.out.println(stu.getName() + ” …. ” + stu.getAge());
}

}

}

class Student implements Comparable {
private String name;
private int age;


Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return this.name;
}

public int getAge() {
return this.age;
}

@Override
public int compareTo(Object o) {
if (!(o instanceof Student)) {
throw new RuntimeException(“不是学生对象”);

}

Student s = (Student) o;

System.out.println(this.name + “—compare to—” + s.name);

if (this.age != s.age) {
System.out.println(this.age – s.age);
return this.age – s.age;
} else {
// if(this.name.equals(s.name)){
// return 0;
// }
// return 1;
System.out.println(“— “+(this.name.compareTo(s.name)));
return this.name.compareTo(s.name);

}

}
}
</pre><br>
<br>
<pre></pre>