HashSet中值的唯一性

偶尔善良 提交于 2020-02-06 05:26:45

1.我们新建这样一个Student类

package com.example.ownlearn;

public class Student {
    int num;
    String name;

    Student(int num,String name){
        this.num = num;
        this.name = name;
    }
}

2.我们知道Set中的值是不可重复的,现在我们做这样一个测试,我们新建两个Student对象,它们的num和name的值完全相同。我们将它们分别插入到Set中,然后将结果打印。

 

package com.example.ownlearn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.HashSet;
import java.util.Iterator;

@SpringBootApplication
public class OwnlearnApplication {

    public static void main(String[] args) {
        SpringApplication.run(OwnlearnApplication.class, args);
        HashSet hashSet = new HashSet();
        Student student = new Student(1,"zhangsan");
        Student student1 = new Student(1,"zhangsan");
        hashSet.add(student);
        hashSet.add(student1);
        Iterator it = hashSet.iterator();
        while (it.hasNext()) {
               System.out.println(JSONObject.toJSON(it.next()));
            }
    }

}

控制台打印出的结果如下:

{"name":"zhangsan","num":1}
{"name":"zhangsan","num":1}

我们可以看到,虽然两个对象的值完全相同但是仍然在Set中添加了两次,我们查询HashMap的源码来寻找答案。

    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)
        //判断hashKey是否冲突(该键的hansh值下所对应的key是否不为null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //如果冲突,如果节点的hansh值(可以看到这里节点的Hash值就是Key的hash值)相同、key相同且不为空,直接将原来的节点赋值给新创建的节点
            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;
    }

Student继承了Object默认的equals和hashCode,对象默认equals方法比较的是引用地址,由于我们新建了两个对象,所以引用地址是不同的,所以造成Set中的值不是我们想要的答案。我们在Student类中添加如下代码来解决问题。

        public int hashCode() {
        return num * name.hashCode();
    }


    @Override
    public boolean equals(Object obj) {
        Student s = (Student)obj;
        return num == s.num  && name.equals(s.name);
    }

我们再次运行程序,可以看到Set中只有一个值了。

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!