Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why HashMap.Entry is transient?

 
Patrio Jensen
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Inside java.util.HashMap class, I see a field transient Entry[] table which is used to store data(key/value pair in this case).

Can someone help me to understand why table is declared as transient?

I tried serializing the HashMap object as mentioned here and could successfully serialize and deserialize.

For that matter even HashTable.elementData, ArrayList.elementData are also declared transient.

Thanks.
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Most Map implementations write their data without the entries, as follows:
- the number of mappings first
- for each mapping, the key first, then the value

For instance, if you have a map with contents {key1=value1, key2=value2, key3=value3}, the contents will be written as follows:
3
key1
value1
key2
value2
key3
value3

This is a tad more efficient than writing the Entry[] table, because then the output would contain more overhead: the array itself, and each Entry element.
 
Patrio Jensen
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob for quick reply.

I tried printing value from Entry[] table of HashMap using reflection and can see that it's storing data.

And also I don't see any data structure (other than Entry[] ) inside HashMap to store key/value pair.
 
Lorand Komaromi
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Patrio Jensen wrote:
And also I don't see any data structure (other than Entry[] ) inside HashMap to store key/value pair.


Just take a look at writeObject(), that's where the entries are serialized...
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It still uses the Entry[] table internally during runtime. The transient keyword only means that the entries will not be serialized / deserialized by default. That's where the readObject and writeObject methods come in; they read / write the entries manually. From the Java 6 source code of HashMap:
s.defaultWriteObject() writes the threshold and loadFactor fields; all other fields are transient. Likewise, s.defaultReadObject() reads those two fields again. The Entry[] table is simply reconstructed instead of serialized and deserialized.>
 
Patrio Jensen
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it now.

Thanks Lorand, Rob.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic