day16Java-Set-HashSet

博客名称
Java-(中级)

Set-HashSet集合

java.util.HashSet
HashSet特点:
底层是一个哈希表(数组+链表/红黑树【jdk8加了红黑树可以提高查询速度】),哈希表保证数据唯一,但是要依赖两个个方法hashCede()和equals()方法。

Collection
  		|--List
  			有序(存储顺序和取出顺序一致),可重复
  		|--Set
  			无序(存储顺序和取出顺序不一致),唯一

注意:有序不等于排序
HashSet保证数据唯一图解
在这里插入图片描述

HashSet:它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。
注意:虽然Set集合的元素无序,但是,作为集合来说,它肯定有它自己的存储顺序,
如果你的的顺序恰好和它的存储顺序一致,这代表不了有序,你可以多存储一些数据,就能看到效果。

Set集合遍历字符串代码演示

public class SetDemo {
    public static void main(String[] args) {
        //创建Set集合
        Set<String> set = new HashSet<String>();

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

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

    }
}

去重复结果展示

world
java
hello
javaee
HashSet集合怎么保证数据唯一的

问题:为什么存储字符串的时候,字符串内容相同的只存储了一个呢?
首先查看的是HashSet集合的add方法是怎么实现的,那就要看源码了,我将HashSet集合add方法相关源码拉取出来。

通过查看add方法的源码,我们知道这个方法底层依赖 两个方法:hashCode()和equals()。

按照方法的步骤来说:	
 	先看hashCode()值是否相同
  				相同:继续走equals()方法
  						返回true:	说明元素重复,就不添加
  						返回false:说明元素不重复,就添加到集合
  				不同:就直接把元素添加到集合

如果类没有重写这两个方法,默认使用的Object()。一般来说不相同。
而String类重写了hashCode()和equals()方法,所以,它就可以把内容相同的字符串去掉。只留下一个。

HashSet类的add()方法源码

public class HashSet {
 	//成员变量
 	private transient HashMap<E, Object> map;
 	//成员变量
 	private static final Object PRESENT = new Object();
    //构造方法
    public HashSet() {
        map = new HashMap<>();
    }
   	//HashSet方法
    public boolean add(E e) {
        return map.put(e, PRESENT) == null;
    }

}

public class HashMap<K, V> {
	static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

 	public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K, V>[] tab;
        Node<K, V> p;
        int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K, V> e;
            K k;
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K, V>) p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
}
HashSet集合存储自定义对象1

需求1:存储自定义对象,并保证元素的唯一性
要求:如果两个对象的成员变量值都相同,则为同一个元素。

目前是不符合我的要求的:因为我们知道HashSet底层依赖的是hashCode()和equals()方法。
而这两个方法我们在学生类中没有重写,所以,默认使用的是Object类。(这段代码没有演示)
这个时候,他们的哈希值是不会一样的,根本就不会继续判断,执行了添加操作。

按照方法的步骤来说:
先看hashCode()值是否相同
相同:继续走equals()方法
返回true: 说明元素重复,就不添加
返回false:说明元素不重复,就添加到集合
不同:就直接把元素添加到集合

代码演示演示一
因为重写的hashCode()返回值每次都是0,所以集合中的对象,比较哈希值的时候那就都是true,那就遥继续比较equals()方法,我在equals()方法中写了System.out.println(this+"----"+s)就是想看在比较的时候调用了多少次equals()方法;

public class SetDemo2 {
    public static void main(String[] args) {
        Set<Student> set = new HashSet<Student>();
        
        Student s1 = new Student("三国演义",18);
        Student s2 = new Student("西游记",20);
        Student s3 = new Student("红楼梦",20);
        Student s4 = new Student("水浒传",20);
        Student s5 = new Student("红楼梦",17);
        Student s6 = new Student("红楼梦",19);
        Student s7 = new Student("三国演义",18);
        Student s8 = new Student("西游记",20);

        set.add(s1);
        set.add(s2);
        set.add(s3);
        set.add(s4);
        set.add(s5);
        set.add(s6);
        set.add(s7);
        set.add(s8);
    }
}


class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        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;
    }
	
	//重写equals()方法
    @Override
    public boolean equals(Object o) {
        Student s = (Student)o;
        System.out.println(this+"----"+s);
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return getAge() == student.getAge() &&
                Objects.equals(getName(), student.getName());
    }
	@Override
    //public int hashCode() {//也可以使用自动生成的Objects中的方法
      // return Objects.hash(name,age);
    //}
	
	//重写hashCode()方法
    @Override
    public int hashCode() {
         return 0;//返回值是0所以添加的Student的所有对象调用hashCode()返回值都是0
    }
		
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

结果:
通过结果可以看出来,添加8个元素要比较18次,如果再多几个元素,比较次数那就要更多,所以说效率太低,需要优化代码。

Student{name='西游记', age=20}----Student{name='三国演义', age=18}
Student{name='红楼梦', age=20}----Student{name='三国演义', age=18}
Student{name='红楼梦', age=20}----Student{name='西游记', age=20}
Student{name='水浒传', age=20}----Student{name='三国演义', age=18}
Student{name='水浒传', age=20}----Student{name='西游记', age=20}
Student{name='水浒传', age=20}----Student{name='红楼梦', age=20}
Student{name='红楼梦', age=17}----Student{name='三国演义', age=18}
Student{name='红楼梦', age=17}----Student{name='西游记', age=20}
Student{name='红楼梦', age=17}----Student{name='红楼梦', age=20}
Student{name='红楼梦', age=17}----Student{name='水浒传', age=20}
Student{name='红楼梦', age=19}----Student{name='三国演义', age=18}
Student{name='红楼梦', age=19}----Student{name='西游记', age=20}
Student{name='红楼梦', age=19}----Student{name='红楼梦', age=20}
Student{name='红楼梦', age=19}----Student{name='水浒传', age=20}
Student{name='红楼梦', age=19}----Student{name='红楼梦', age=17}
Student{name='三国演义', age=18}----Student{name='三国演义', age=18}
Student{name='西游记', age=20}----Student{name='三国演义', age=18}
Student{name='西游记', age=20}----Student{name='西游记', age=20}

优化代码演示演示
优化代码其实只用优化hashCode()方法就行,如果Student每个对象的hashCode()值不一样就不会(在这里就可以根据学生的姓名和年龄去计算哈希值,只有两个有一个不一样就认为不是一样的元素),去比较equals()这样就提升了效率。

public class SetDemo2 {
    public static void main(String[] args) {
        Set<Student> set = new HashSet<Student>();
		
        Student s1 = new Student("三国演义",18);
        Student s2 = new Student("西游记",20);
        Student s3 = new Student("红楼梦",20);
        Student s4 = new Student("水浒传",20);
        Student s5 = new Student("红楼梦",17);
        Student s6 = new Student("红楼梦",19);
        Student s7 = new Student("三国演义",18);
        Student s8 = new Student("西游记",20);

        set.add(s1);
        set.add(s2);
        set.add(s3);
        set.add(s4);
        set.add(s5);
        set.add(s6);
        set.add(s7);
        set.add(s8);
    }
}

Student实体类,hashCode()方法改进

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        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 boolean equals(Object o) {
        Student s = (Student) o;
        System.out.println(this + "----" + s);//查看equals执行的数

        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return getAge() == student.getAge() &&
                Objects.equals(getName(), student.getName());
    }
    @Override
    public int hashCode() {
        // return 0;
        //return this.name.hashCode() +this.age; 有漏洞
        //s1:this.name.hashCode()=30  this.age=20
        //s2:this.name.hashCode()=20  this.age=30
        //通过上面的例子可以看出来哈希值,和年龄值不一样但是总数是一样的,还是有漏洞的得改进

        return this.name.hashCode() + this.age * 15;//尽可能的区分,我们可以把它们乘以一些整数

    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

优化后的hashCode()方法再看equslas()执行次数
只有2次

Student{name='三国演义', age=18}----Student{name='三国演义', age=18}
Student{name='西游记', age=20}----Student{name='西游记', age=20}
HashSet集合存储自定义对象2

HashSet集合存储自定义对象并遍历。如果对象的成员变量值相同即为同一个对象

注意了:
你使用的是HashSet集合,这个集合的底层是哈希表结构。
而哈希表结构底层依赖:hashCode()和equals()方法。(切记,切记。)
如果你认为对象的成员变量值相同即为同一个对象的话,你就应该重写这两个方法。

代码演示
测试类

public class DogDemo {
    public static void main(String[] args) {
        Set<Dog> set = new HashSet<>();

        //创建Dog对象
        Dog d1 = new Dog("秦桧", 25, "红色", '男');
        Dog d2 = new Dog("高俅", 22, "黑色", '女');
        Dog d3 = new Dog("秦桧", 25, "红色", '男');
        Dog d4 = new Dog("秦桧", 20, "红色", '女');
        Dog d5 = new Dog("魏忠贤", 28, "白色", '男');
        Dog d6 = new Dog("李莲英", 23, "黄色", '女');
        Dog d7 = new Dog("李莲英", 23, "黄色", '女');
        Dog d8 = new Dog("李莲英", 23, "黄色", '男');

        //添加Dog对象到Set集合
        set.add(d1);
        set.add(d2);
        set.add(d3);
        set.add(d4);
        set.add(d5);
        set.add(d6);
        set.add(d7);
        set.add(d7);

        //遍历集合
        for(Dog d:set){
            System.out.println(d);
        }
    }
}

实体类

public class Dog {
    private String name;
    private int age;
    private String color;
    private char sex;

    public Dog(String name, int age, String color, char sex) {
        this.name = name;
        this.age = age;
        this.color = color;
        this.sex = sex;
    }

    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;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                ", sex=" + sex +
                '}';
    }

    //重写hashCode()方法和equals()方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Dog dog = (Dog) o;
        return age == dog.age &&
                sex == dog.sex &&
                Objects.equals(name, dog.name) &&
                Objects.equals(color, dog.color);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, age, color, sex);
    }
}

结果:

Dog{name='高俅', age=22, color='黑色', sex=}
Dog{name='秦桧', age=20, color='红色', sex=}
Dog{name='秦桧', age=25, color='红色', sex=}
Dog{name='魏忠贤', age=28, color='白色', sex=}
Dog{name='李莲英', age=23, color='黄色', sex=}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值