Map for Java Collection Source Analysis: Super Interface Map_One Point Classroom (Multi-shore College)

Posted by pmaonline on Tue, 10 Sep 2019 07:53:58 +0200

Array and linked list have their own advantages and disadvantages in data processing. Array query is fast and insertion is slow. Linked list performs well in insertion, but the query is weak. Hash table integrates the advantages of array and linked list, and has good speed in insertion and search. The HashMap we will analyze later is implemented based on hash tables, but the performance of the HashMap is further improved by introducing red and black trees in JDK 1.8. This paper mainly analyses the definition of Map in JDK.

Interface Map

Map is defined as:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

That is, based on the key-value data format, and the key value can not be repeated, each key corresponds to a unique value. Map keys can also be null and not heavy.

Before we analyze the method of its definition, we need to look at the Map.Entry interface.

Interface Map.Entry

The data stored in Map needs to implement this interface, which mainly provides the operation of key and value, and is also the operation we use most. Let's first analyze it:

// Get the corresponding key
K getKey();

// Get the corresponding value
V getValue();

// Replace the original value
V setValue(V value);

// Hope we can implement equals and hashCode
boolean equals(Object o);
int hashCode();

// From 1.8 onwards, there are four comparative methods.
public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
        return (Comparator<Map.Entry<K, V>> & Serializable)
            (c1, c2) -> c1.getKey().compareTo(c2.getKey());
}

Important methods

// Returns the current number of data
int size();

// Is it empty?
boolean isEmpty();

// To determine whether a key is included, the equals method of the key is used, so the key must implement it.
boolean containsKey(Object key);

// It is also based on the equals method to determine whether the value saved by the key is value.
boolean containsValue(Object value);

// Get the corresponding value value by key
V get(Object key);

// Save in key-value
V put(K key, V value);

// Remove a key-value pair
V remove(Object key);

// Adding from other Map s
void putAll(Map<? extends K, ? extends V> m);

// empty
void clear();

// Return all keys to the Set set, because the key is not heavy, and the Set is not heavy.
Set<K> keySet();

// Returns all values
Collection<V> values();

// Return key-value pairs to Set
Set<Map.Entry<K, V>> entrySet();

// Hope we can implement equals and hashCode
boolean equals(Object o);
int hashCode();

In addition, there are some default methods related to Java 8, which are not shown one by one.

default V getOrDefault(Object key, V defaultValue) {
    V v;
    return (((v = get(key)) != null) || containsKey(key))
        ? v
        : defaultValue;
}

Super Implementation Class: AbstractMap

For AbstractCollection, AbstractMap has a similar function, mainly providing some implementations of methods to facilitate inheritance. Now let's see what methods it implements:

 // Return size, where size is based on entrySet size
public int size() {
    return entrySet().size();
}

public boolean isEmpty() {
    return size() == 0;
}

//entrySet-based operation
public boolean containsKey(Object key) {
        Iterator<Map.Entry<K,V>> i = entrySet().iterator();
        if (key==null) {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    return true;
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    return true;
            }
        }
        return false;
    }

public boolean containsValue(Object value) {
    //...
}

public V get(Object key) {
    //...
}

public V remove(Object key) {
    //...
}

public void clear() {
    entrySet().clear();
}

In addition, two variables are defined:

transient Set<K>        keySet;
transient Collection<V> values;

The default implementation method is also provided. Let's just look at one of them.

public Set<K> keySet() {
    Set<K> ks = keySet;
    if (ks == null) {
        ks = new AbstractSet<K>() {
            public Iterator<K> iterator() {
                return new Iterator<K>() {
                    private Iterator<Entry<K,V>> i = entrySet().iterator();

                    public boolean hasNext() {
                        return i.hasNext();
                    }

                    public K next() {
                        return i.next().getKey();
                    }

                    public void remove() {
                        i.remove();
                    }
                };
            }

            public int size() {
                return AbstractMap.this.size();
           }

            public boolean isEmpty() {
               return AbstractMap.this.isEmpty();
            }

            public void clear() {
                AbstractMap.this.clear();
            }

            public boolean contains(Object k) {
                return AbstractMap.this.containsKey(k);
            }
        };
        keySet = ks;
    }
    return ks;
}

In addition to the above related methods, AbstractMap also implements equals, hashCode, toString, clone and other methods, which can save a lot of work in the specific implementation.

Thank you for seeing it. If you can help me, please give me a compliment.

More experience and technology are welcome to come and learn together. A Little Classroom - Online Learning Platform for Dreams http://www.yidiankt.com/

[Pay attention to the public number and reply to "1" for free - [java Core Knowledge Points]

QQ discussion group: 616683098

QQ: 3184402434

Students who want to study in depth can study and discuss with QQ ~and have a full set of resources to share, experience to explore, wait for you!

Topics: Programming JDK Java