Java_map의 키는 사용자 정의 대상입니다

4191 단어
먼저 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 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());
}

해시맵의 판단.
만약hash값mod 이후의 인덱스라면, 인덱스가 충돌한 후 키가 같은지, 같으면 비교하지 않고, 다르면 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[] tab; Node 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 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)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;
}

좋은 웹페이지 즐겨찾기