Java 单列集合Set及其子实现类

接口Set:

Set和List一样,也继承于Collection,是集合的一种。和List不同的是,Set内部实现是基于Map的,所以Set取值时不保证数据和存入的时候顺序一致,并且不允许空值,不允许重复值。

Set:底层数据结构是一个哈希表,能保证元素是唯一的,元素不重复!
它通过它的子实现了HashSet集合去实例化,HashSet集合底层是HashMap集合的实例!

Set集合存储字符串元素并遍历:

public class SetDemo {

    public static void main(String[] args) {

        //创建Set集合对象
        Set<String> set = new HashSet<String>() ;

        //添加元素
        set.add("hello");
        set.add("java") ;
        set.add("java") ;
        set.add("world") ;
        set.add("world") ;
        set.add("world") ;

        //增强for遍历
        for(String s :set){
            System.out.println(s);
        }
    }
}

Set的子实现类HashSet:

HashSet集合的add()方法,底层是依赖于双列集合HashMap的put(K key,V value)来实现的

put(K key,V value):底层又依赖于HashCode()和equals()方法,传递添加元素的时候,首先判断的是每一个元素对应的HashCode值是否一样,如果HashCode值一样,还比较他们的equals()方法,由于现在集合存储的是String类型,String类型本身重写了equals()方法,所以,默认比较的是内容是否相同,如果内容相同,这里最终返回的就是第一次存储的那个元素,由这两个方法保证元素唯一性!

import java.util.HashSet;  
public class HashSetDemo {

    public static void main(String[] args) {

        //创建一个HashSet集合对象
        HashSet<Student> hs = new HashSet<Student>() ;

        //创建学生对象
        Student s1 = new Student("刘德华", 27) ;
        Student s2 = new Student("周润发", 25) ;
        Student s3 = new Student("周星星", 26) ;
        Student s4 = new Student("邓超", 29) ;
        Student s5 = new Student("胡歌", 23) ;
        Student s6 = new Student("吴奇隆", 27) ;

        //给集合中添加学生对象
        hs.add(s1) ;
        hs.add(s2) ;
        hs.add(s3) ;
        hs.add(s4) ;
        hs.add(s5) ;
        hs.add(s6) ;

        //增强for遍历
        for(Student s : hs){
            System.out.println(s.getName()+"---"+s.getAge());
        }
    }
}
public class Student {

    private String name ;
    private int age ;

    public Student() {
        super();
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    //自动生成
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }   
}

Set的子实现类TreeSet:

TreeSet:Set集合中的一个重点

  1. TreeSet集合底层是依赖于TreeMap的实例,而TreeMap是依赖于红黑树(二叉树)结构实现的
    分两种:
    自然排序:
    比较器排序
    这种排序的使用取决于开发者是用什么样的构造方法

TreeSet存储对象的时候, 可以排序, 但是需要指定排序的算法

Integer能排序(有默认顺序), String能排序(有默认顺序), 自定义的类存储的时候出现异常(没有顺序)

如果想把自定义类的对象存入TreeSet进行排序, 那么必须实现Comparable接口
在类上implement Comparable
重写compareTo()方法
在方法内定义比较算法, 根据大小关系, 返回正数负数或零
在使用TreeSet存储对象的时候, add()方法内部就会自动调用compareTo()方法进行比较, 根据比较结果使用二叉树形式进行存储

2.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());
        }
    }
}

当我们自定义对象时就得重写了compareTo()方法:

public class TreeSetDemo2 {

    public static void main(String[] args) {

        //创建TreeSet集合对象
        TreeSet<Student> ts = new TreeSet<Student>() ;//

        //创建学生对象
        Student s1 = new Student("linqingxia", 28) ;
        Student s2 = new Student("fengqingy", 28) ;
        Student s3 = new Student("gaoyuanyuan", 27) ;
        Student s4 = new Student("liushishi", 26) ;
        Student s5 = new Student("wanglihong", 29) ;
        Student s6 = new Student("zhangguorong", 30) ;
        Student s7 = new Student("zhangguorong", 30) ;

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);
        ts.add(s7);

        //遍历
        for(Student s : ts){
            System.out.println(s.getName()+"---"+s.getAge());
        }
    }   
}
public class Student implements Comparable<Student>{

    private String name ;
    private int age ;
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    //重写了compareTo()方法
    @Override
    public int compareTo(Student s) {
//      return 0;
        //排序的代码了,需要定义排序的条件
        //主要条件:按照学生的年龄从小到大进行排序
        int num =s.age - this.age ;//年龄从大到小 
//      return num ;
        //当num==0认为年龄一样,年龄一样,不代表姓名的的内容是否相同,需要自己给出次要条件
        int num2 = num==0 ? this.name.compareTo(s.name): num ;
        return num2 ;
    }   
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值