Why is the member field in the java.util.HashMap table temporary?

I found out that the keyword transientprevents the storage of the values of the instance fields declared with the keyword transientwhen the object is serialized.

Below is the code from java.util.HashMap:

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

             ....
             static class Node<K,V> implements Map.Entry<K,V> {...}
             transient Node<K,V>[] table;
}

Why are instance field values tablenot part of serialization? Because the field values tableare the actual contents of the instance class HashMapin terms of implementation.

Note: here is one exercise to use the transient keyword.

+4
source share
2 answers

, ?

  • , . , OutputStream Window.
  • , . , .

, Member ?

(2). readObject HashMap. table .

+2

HashMap , : . - -, - -.

"" , , 2 , .

. :

   public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        // Find a power of 2 >= initialCapacity
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        this.loadFactor = loadFactor;
        threshold = (int)(capacity * loadFactor);
        table = new Entry[capacity];
        init();
    }
0

Source: https://habr.com/ru/post/1606202/


All Articles