黑马程序员技术交流社区
标题:
TreeSet是依靠TreeMap来实现的
[打印本页]
作者:
H_shaohui
时间:
2016-5-3 21:38
标题:
TreeSet是依靠TreeMap来实现的
TreeSet是一个有序集合,TreeSet中的元素将按照升序排列,缺省是按照自然排序进行排列,意味着TreeSet中的元素要实现Comparable接口。或者有一个自定义的比较器。
我们可以在构造TreeSet对象时,传递实现Comparator接口的比较器对象。
import
java.util.Iterator;
import
java.util.*
;
public
class
TreeSetTest {
public
static
void
main(String[] args) { Set ts
=
new
TreeSet(); ts.add(
"abc"
); ts.add(
"xyz"
); ts.add(
"rst"
); Iterator it
=
ts.iterator();
while
(it.hasNext()) { System.out.println(it.next()); } }}
输出结果:
abc
rst
xyz
打印结果不是和先前加入的顺序一样,它是按照一个字母的排序法进行排序的。这是因为String 类实现了Comparable接口。
如果我们自己定义的一个类的对象要加入到TreeSet当中,那么这个类必须要实现Comparable接口。
package
test.treeset;
import
java.util.Iterator;
import
java.util.Set;
import
java.util.TreeSet;
public
class
test_treeset { @SuppressWarnings(
"unchecked"
)
public
static
void
main(String[] args) { Set ts
=
new
TreeSet(); ts.add(
new
Teacher("zhangsan", 1
)); ts.add(
new
Teacher("lisi", 2
)); ts.add(
new
Teacher("wangmazi", 3
)); ts.add(
new
Teacher("wangwu",4
)); ts.add(
new
Teacher("mazi", 3
)); Iterator it
=
ts.iterator();
while
(it.hasNext()) { System.out.println(it.next()); } }}
class
Teacher
implements
Comparable {
int
num; String name; Teacher(String name,
int
num) {
this
.num =
num;
this
.name =
name; }
public
String toString() {
return
"学号:" + num + "\t\t姓名:" +
name; }
//
o中存放时的红黑二叉树中的节点,从根节点开始比较
public
int
compareTo(Object o) { Teacher ss
=
(Teacher) o;
int
result = num < ss.num ? 1 : (num == ss.num ? 0 : -1);
//
降序
//
int result = num > ss.num ? 1 : (num == ss.num ? 0 : -1);
//
升序
if
(result == 0
) { result
=
name.compareTo(ss.name); }
return
result; }}
运行结果:
学号:4 姓名:wangwu
学号:3 姓名:mazi
学号:3 姓名:wangmazi
学号:2 姓名:lisi
学号:1 姓名:zhangsan
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2