1.Set接口的实现类有哪些?
HashSet:HashSet的底层其实就是一个HashMap所以是不能重复的, 只是我们add的时候只使用了HashMap的key部分。
TreeSet:可以对Set集合进行排序,默认自然排序
2.TreeSet存放自定义类型如何实现有序的?
分别是采用Comparable接口Comparator接口实现的
总结:Set集合的特点就是无序,不可重复对比List集合是有序的,可以重复 此处的有序,无序指的是插入数据时候的顺序和取出数据时候的顺序是不一样的
结合代码分别使用Comparable接口和Comparator接口来实现有序排列自定义类型
1.实现Comparable接口
对于存放在Set中的对象需要实现Comparable接口代码如下:
public class Student implements Comparable{
int age;
String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public Student() {
}
@Override
public int compareTo(Object o) {
if(!(o instanceof Student)){ //左边是对象右边是类,当左边是右边类或者是子类的对象时返回True
throw new RuntimeException("o参数不合法");
}
//return this.age-((Student) o).age;根据年龄正序
return ((Student) o).age-this.age; //根据年龄倒序
}
}
public class TreeSetTest01 {
public static void main(String[] args) {
Student zs = new Student(20, "张三");
Student ls = new Student(30, "李四");
Student ww = new Student(40, "王五");
Set set = new TreeSet();
set.add(ww);
set.add(zs);
set.add(ls);
for (Iterator iterator = set.iterator();iterator.hasNext();){
Student s = (Student) iterator.next();
System.out.println("name:"+ s.name+"---"+s.age);
}
}
}
2.实现Comparator接口,对象不需要实现接口,只需要在比较的时候实现Comparator接口即可
public class Person{
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public Person() {
}
}
public class TreeSetTest02 {
public static void main(String[] args) {
Person zs = new Person(20, "zs");
Person ls = new Person(30, "ls");
Person ww = new Person(40, "ww");
// 创建一个匿名的内部类
Set set = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(!(o1 instanceof Person)){
throw new RuntimeException("o1参数非法");
}
if(!(o2 instanceof Person)){
throw new RuntimeException("o2参数非法");
}
return ((Person) o1).age-((Person) o2).age;
}
});
set.add(ls);
set.add(zs);
set.add(ww);
for(Iterator it = set.iterator(); it.hasNext();){
Person s = (Person) it.next();
System.out.println("name"+ s.name+"---"+s.age);
}
}
}