Java_map的key為自定義對象


首先自定義Key對象

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

import java.util.Objects;

/**
 * @author AganRun
 * @date 2019/10/16
 */
@Getter
@Setter
@AllArgsConstructor
public class SelfKey {

    private String first;
    private String second;
    private String third;

    @Override
    public int hashCode() {
        return first.hashCode() + second.hashCode() + third.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
//        super.equals(obj);
        SelfKey selfKey = (SelfKey) obj;
        boolean equals1 = Objects.equals(this.first, selfKey.getFirst());
        boolean equals2 = Objects.equals(this.second, selfKey.getSecond());
        boolean equals3 = Objects.equals(this.third, selfKey.getThird());
        return equals1 && equals2 && equals3;
    }
}

測試類

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author AganRun
 * @date 2019/10/16
 */
@Slf4j
public class HashMapSelfKeyTest {

    @Test
    public void test(){
        SelfKey selfKey1 = new SelfKey("1","2","3");
        SelfKey selfKey2 = new SelfKey("3","2","1");

        Map<SelfKey, String> map = new HashMap<>();
        map.put(selfKey1, "value1");
        map.put(selfKey2, "value2");

        /**
         * 如果不重寫hashcode和equals方法,至於put時的對象可以取出對應的值
         * 第一個輸出:06:53:50.193 [main] INFO com.agan.map.HashMapSelfKeyTest - null
         * 第二個輸出:06:53:50.195 [main] INFO com.agan.map.HashMapSelfKeyTest - value1
         *
         * 如果只重寫hashCode方法。equals比較時依舊比較內存地址,導致不通過
         * 輸出結果和第一個相同
         *
         * 自定義重寫了hashCode和Equeals方法后
         * 07:02:47.469 [main] INFO com.agan.map.HashMapSelfKeyTest - value1
         * 07:02:47.472 [main] INFO com.agan.map.HashMapSelfKeyTest - value1
         */
        log.info(map.get(new SelfKey("1", "2", "3")));
        log.info(map.get(selfKey1));
    }
}

在這里再寫兩個其他的發現。
equals在程序執行時可能會調用多次,比如可以在equals中打印語句。

toString方法會調用這個方法的HashCode()方法

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

HashMap的判斷

如果hash值mod之后的索引,索引沖突后會看key是否相同,如果相同則不再比較,如果不同再比較equals


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

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
    
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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM