What is the difference between Collections.emptyMap() and new HashMap? Table comparison + source code

Small thoughts:

Recently, my mood is more complicated, ε=(′ο`*))), probably the time has come, coupled with the uncertainty of the future, the state has not been good;

Seeing that many bigwigs have found summer internships, I am still here. First, I feel that the atmosphere is not bad (except for the Internet environment, there is no way for the general environment, no one wants to do this), and second, I feel that everyone compares Friendly, let’s see if I can become a full-time member. I hope there will be news before late August. This is probably the last DDL;

And record some daily, I plan to ask for leave at the school の group meeting tomorrow. The frequency of asking for leave once a month is actually okay. The state is very bad recently, and I really don’t want to go back to the group meetingε=(′ο`*)));

Maybe the lab model could be improved with distillation? Then find a way to add feature information? But in fact, I don’t seem to understand the logic of adding from 6 different dimensions in 2023, and I have to change the code;

Annoyed to death, I hope the autumn recruiting and autumn recruiting will go well, and then half of the time is better than the current situation;

(|3[▓▓] good night

What is the difference between Collections.emptyMap() and new HashMap?

characteristic

Collections. emptyMap()

new HashMap()

memory usage

Even smaller, it’s a static singleton. No matter how many times Collections.emptyMap() is called, it will only return a reference to the same object, so its memory footprint is very small.

bigger. Each HashMap instance has an internal array for storing key-value pairs, even an empty HashMap will have an array of the default size.

variability

Returns an empty immutable Map. No elements can be added or removed from this Map.

Returns a mutable Map. Elements can be added, removed, or modified to it.

performance

more efficient. If you need a Map that doesn’t contain any elements and never changes, it’s better to use Collections.emptyMap().

If you need a map that can be modified, you should use new HashMap().

thread safety

thread safe. Because it is immutable, multiple threads can access it simultaneously without conflict.

Not thread safe. If multiple threads modify HashMap at the same time, it may cause data inconsistency.

Null values and Null keys

Null keys or null values are not allowed.

One null key and multiple null values are allowed.

method implementation

The put method is not implemented, and an UnsupportedOperationException will be thrown if an attempt is made to call the put method.

All methods of the Map interface are implemented.

Combined source code analysis difference:

Memory aspect:

Collections.emptyMap() returns an empty immutable Map, which is a static singleton. No matter how many times Collections.emptyMap() is called, it will only return a reference to the same object, so its memory footprint is very small. This is because it does not need to store any key-value pairs, nor does it need to maintain any internal data structures.

// Collections.java

public class Collections {

    public static final <K,V> Map<K,V> emptyMap() {

        return (Map<K,V>) EmptyMap. EMPTY_MAP;

    }



    private static class EmptyMap extends AbstractMap<Object, Object> {

        //...

    }

}

new HashMap() will create a new HashMap instance. Each HashMap instance has an internal array for storing key-value pairs, even an empty HashMap will have an array of the default size (unless a smaller initial size is specified). Therefore, even an empty HashMap will take up more memory than Collections.emptyMap().

// HashMap.java

public class HashMap<K,V> extends AbstractMap<K,V> {

    transient Node<K,V>[] table;

    //...

}

Therefore, if you need an empty Map and don’t intend to add any elements to it, it is more memory efficient to use Collections.emptyMap(). If you need a Map where elements can be added, removed or modified, then you should use new HashMap(), but be aware that even an empty HashMap will take up some memory.

Immutability:

Collections.emptyMap() returns an empty immutable Map, which is achieved by returning an internal static class EmptyMap, which does not implement methods for adding or removing elements.

// Collections.java

public class Collections {

    public static final <K,V> Map<K,V> emptyMap() {

        return (Map<K,V>) EmptyMap. EMPTY_MAP;

    }



    private static class EmptyMap extends AbstractMap<Object, Object> {

        //...

    }

}

And new HashMap() returns a mutable Map, which has an internal array for storing elements, and a series of methods for adding, deleting, and modifying elements.

// HashMap.java

public class HashMap<K,V> extends AbstractMap<K,V> {

    transient Node<K,V>[] table;

    //...

}

Performance:

Since the Map returned by Collections.emptyMap() is immutable, it has only one instance, which saves memory.

// Collections.java

public class Collections {

    public static final <K,V> Map<K,V> emptyMap() {

        return (Map<K,V>) EmptyMap. EMPTY_MAP;

    }

}

And HashMap creates a new instance every time new is called.

// HashMap.java

public class HashMap<K,V> extends AbstractMap<K,V> {

    public HashMap() {

        //...

    }

}

Thread Safety:

The Map returned by Collections.emptyMap() is thread-safe because it is immutable.

HashMap is not thread-safe. If you need thread safety, you can use Collections.synchronizedMap or ConcurrentHashMap.

Empty values and Null keys:

Collections.emptyMap() does not allow null keys or null values, which is achieved by directly returning null in the get method.

// Collections.java

public class Collections {

    private static class EmptyMap extends AbstractMap<Object, Object> {

        public V get(Object key) {

            return null;

        }

    }

}

And HashMap allows one null key and multiple null values, which is achieved by checking whether the key is null in the getNode method.

// HashMap.java

public class HashMap<K,V> extends AbstractMap<K,V> {

    final Node<K,V> getNode(int hash, Object key) {

        if (key == null) {

            //...

        }

    }

}

Method implementation:

The Map returned by Collections.emptyMap() does not implement the put method. If you try to call the put method, an UnsupportedOperationException will be thrown.

// Collections.java

public class Collections {

    private static class EmptyMap extends AbstractMap<Object, Object> {

        public V put(K key, V value) {

            throw new UnsupportedOperationException();

        }

    }

}

And HashMap implements all methods of Map interface.

// HashMap.java

public class HashMap<K,V> extends AbstractMap<K,V> {

    public V put(K key, V value) {

        //...

    }

}

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge Java skill treeHome pageOverview 118850 people are studying systematically