HashSet集合介绍和哈希值

Set接口

Set接口和List接口一样,同样继承自Collection接口,他与Collection接口中的方法

基本一致,与List接口不同的是:Set接口中元素无序,会以某种规则保证存入的元素不出现重复。

Set集合多个子类,为HashSet、LinkedHashSet两个集合

HashSet集合介绍

它存储的元素是不可重复的,并且元素都是无序的(存取顺序不一致)。

HashSet底层的实现是一个HashMap支持,

HashSet是根据对象的哈希值来确定元素在结合中的存储位置,因此具有良好的存取和查找性能。

特点:

  1.不允许存储重复的元素。

  2.没有索引,没有带索引的方法,也不能使用普通的for循环遍历

  3.是一个无序的集合,存储元素和取出元素的顺序有可能不一致

  4.底层是一个哈希表结构(查询的速度非常的快)

    public static void main(String[] args) {
        HashSet<Integer> set = new HashSet<>();
        set.add(1);
        set.add(3);
        set.add(2);
        set.add(1);
        //使用迭代器遍历set集合
        Iterator<Integer> it = set.iterator();
        while (it.hasNext()){
            Integer n = it.next();
            System.out.println(n);
        }
        //增强for遍历set集合
        System.out.println("===============");
        for (Integer i : set){
            System.out.println(i);
        }
    }

哈希值

是一个十进制的整数,由系统随机给出的(对象的地址值,是一个逻辑地址,

是模拟出来得到的地址,不是数据实际存储的物理地址)

在Object类有一个方法,可以获取对象的哈希值

 

系统给出

    public static void main(String[] args) {
        //Person类继承了Object类,所以可以使用Object类的hashCode方法
        Person p1 = new Person();
        int i = p1.hashCode();
        System.out.println(i);

        Person p2 = new Person();
        int i1 = p2.hashCode();
        System.out.println(i1);
    }

 

 重写hashCode方法

public class Person extends Object{
    //重写hashCode方法
    @Override
    public int hashCode() {
        return 1;
    }
    
}

 

而String类的哈希值String类重写Object类的hashCode方法

        String s1 = new String("abc");
        String s2 = new String("abc");
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());    

 

 

 

posted @ 2022-07-06 10:44  魔光领域  阅读(60)  评论(0编辑  收藏  举报