hashMap中的get方法

HashMap的get方法的实现,其判断标准是通过hashCode和equals方法。

/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * 

More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * *

A return value of {@code null} does not necessarily * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */ public V get(Object key) { if (key == null) return getForNullKey(); Entry entry = getEntry(key); return null == entry ? null : entry.getValue(); } /** * Offloaded version of get() to look up null keys. Null keys map * to index 0. This null case is split out into separate methods * for the sake of performance in the two most commonly used * operations (get and put), but incorporated with conditionals in * others. */ private V getForNullKey() { if (size == 0) { return null; } for (Entry e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; }

/**
     * Returns the entry associated with the specified key in the
     * HashMap.  Returns null if the HashMap contains no mapping
     * for the key.
     */
    final Entry getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        for (Entry e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

 

hashMap(key,value)的key和value都可以是null。

 

解析:

1、get的时候,如果key==null,判断Map的长度也为空的话就返回null,如果Map长度不为空,则e也不空,遍历table[0],返回e.value.

2、getEntry的时候,首先要获取hash(key)的值,通过hash&table.length获取到的hashCode值得到entry在桶中存放的位置,判断如果传入的key与要获得key的hash相等的话并且key.equals(e.key)也相等,则返回entry,如果返回的jentry不为空的话,则getValue值。

你可能感兴趣的:(java程序员面试笔试)