HashMap,你是怎么做到的Key重复?

简介: HashMap,你是怎么做到的Key重复?

HashMap,你是怎么做到的Key重复?

小朱: 今天遇到了一件奇怪的事?
大牛: 什么事?
小朱: 我把对象当作Key放到HashMap里,Key重复了?
大牛: Key重复了?出现了两个一样的Key?
小朱: 是啊!
大牛: 有意思,你要是取值,他会返给你哪个?
小朱: 这个没试过.
大牛: 让我看看你的代码.
小朱: 好的.

代码

Student

public class Student {

    private Integer id;
    
    private String name;

    //get和set省略
    public Student(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id) &&
                Objects.equals(name, student.name);
    }
}

Test

public class Test {
    
    public static void main(String[] args) {
        Student student1 = new Student(1,"小朱");
        Student student2 = new Student(2,"大牛");
        HashMap<Student,String> hashMap = new HashMap<>();
        hashMap.put(student1,"菜鸡");
        hashMap.put(student2,"大神");
        //这个方法不需要穿Student,为了验证是同一个对象所以改动了一下
        updateValue(hashMap,student1);
        System.out.println(hashMap.size());
    }

    public static HashMap<Student,String> updateValue(HashMap<Student,String> hashMap,Student student){
        Student student1 = new Student(1,"小朱");
        System.out.println(student1.equals(student));
        hashMap.put(student1,"新手");
        return hashMap;
    }
}

运行结果

true
3

小朱: 代码就是这样,为了验证这个两个对象是相同的,我该遭了updateValue方法.本来只要传HashMap<Student,String>,为了验证我外加了一个Student.
大牛: 哦,确实有意思,你怎么不尝试写个取出元素的方法,例如:

getValue

public static void getValue(HashMap<Student,String> hashMap){
    Student student1 = new Student(1,"小朱");
    System.out.println(hashMap.get(student1));
}

小朱: 我试下.

输出结果

null

小朱: 为什么?我重写了equals它们对象都相等啊?为什么取不出来!
大牛: HashMap源码了解一下.

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

/**
 * Implements Map.put and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
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;
}

大牛: 还有下面这段.

public static void main(String[] args) {
    Student student1 = new Student(1,"小朱");
    Student student2 = new Student(1,"小朱");
    System.out.println(student1.equals(student2));
    System.out.println(student1.hashCode());
    System.out.println(student2.hashCode());
}

小朱: 我跑一下看看.

true
1456208737
288665596

小朱: 我明白了,HashMap先判断hashCode值,如果不相同则算这两个对象不相同,如果相同防止哈希冲突,再去判断equals,我这边只重写了equals方法,而hashCode没重写才出现了这个问题.
大牛: 只重写了equals方法,而hashCode不重写,违背了java规范.虽然某些情况下可以,但是用在HashSet,HashMap等等地方就会出现问题.所以不要偷懒哦.
小朱: 学到了.

各位读者根据这个题目,可以探索出一个面试题.

student1.equals(student2) //为true时,
hashMap.put(student1,"菜鸡");
hashMap.put(student2,"大神");
System.out.println(hashMap.size()); //是多少?

去考考你们的小伙伴吧.

相关文章
|
7月前
|
存储
HashMap HashTable ConcurrentMap 中key value是否可以为null
HashMap HashTable ConcurrentMap 中key value是否可以为null
49 0
|
算法 Java 程序员
Java HashMap 在获得 Key 的 Hash 值的时候用的是什么算法
Java 在 HashMap Key 的 Hash 值的时候用的的是自己 Object 中的 hashCode() 算法。
146 0
|
算法 Java
Java HashMap 的中 key 的哈希值是如何计算的,为何这么计算?
Java HashMap 的中 key 的哈希值是如何计算的,为何这么计算?
Java HashMap 的中 key 的哈希值是如何计算的,为何这么计算?
|
存储 Java
为什么不建议使用实数作为 HashMap 的 key?
为什么不建议使用实数作为 HashMap 的 key?
165 0
|
存储 Java
Java - HashMap 的 key 更改后能否正确获取 value?
Java - HashMap 的 key 更改后能否正确获取 value?
276 0
HashMap遍历所有的key和value
HashMap遍历所有的key和value
427 0
|
Java
JAVA HashMap单key多value的实现及迭代器打印(附源码)
(转载请注明出处:http://blog.csdn.net/buptgshengod) 1.背景       在处理大量数据的时候,当遇到单键值多数据的情况下可以选择用HashMap配合ArrayList进行存储,使用迭代器打印相关数据。如下图: 2.代码实现 import java.awt.List; import java.io.BufferedReader; imp
10296 0
HashMap通过value反查key
这是今天做了一道字符串的问题,一直MLE,所以想到了减少Map里对应关系数量来降低内存开销。随手谷歌,整理出了如下资料。       如果效率优先的话还是写俩Map吧。 import java.
723 0