黑马程序员技术交流社区
标题:
TreeSet使用比较器和泛型的初级结合
[打印本页]
作者:
itheima_llt
时间:
2015-4-17 12:22
标题:
TreeSet使用比较器和泛型的初级结合
查阅API,得到:
“TreeSet(Comparator<? super E> comparator)
构造一个新的空 TreeSet,它根据指定比较器进行排序。”
现在把ArrayList改成TreeSet
##六、比较器的泛型定义方式分析
```
import java.util.*;
class GenericDemo6
{
public static void main(String[] args)
{
//方式二和方式一选其一,打开对于的代码块就可以了
TreeSet<Student> al1 = new TreeSet<Student>();//方式一让学生自身具备比较性
//TreeSet<Student> al1 = new TreeSet<Student>(new Comp());//方式二,让集合具备比较性
al1.add(new Student("Student--abc--1"));
al1.add(new Student("Student--abc--3"));
al1.add(new Student("Student--abc--2"));
}
}
class Person
{
private String name;
Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
/*
<? super Student>所以<>可以填<Student>或者<Person>,
注意<? super Student>的Student是跟着TreeSet<Student>中的Student走的!
*/
//这个是让学生自身具备比较性
class Student extends Person implements Comparable<Person>
{
Student(String name)
{
super(name);
}
public int compareTo(Person s)
{
//Person s = new Student();这个是可以接受进来的,所以能比较
return this.getName().compareTo(s.getName());
}
}
/*
<? super Student>所以<>可以填<Student>或者<Person>,
注意<? super Student>的Student是跟着TreeSet<Student>中的Student走的!
*/
/*
//这是让集合具备比较性
class Comp implements Comparator<Person>
{
public int compare(Person s1,Person s2)
{
//Person s1 = new Student("abc1");所以是可以接受Student和Student的父类
return s1.getName().compareTo(s2.getName());
}
}
*/
```
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2