Java Hash Table Issue with Object Reference

2019-07-07 02:47发布

问题:

I have a Hash Table like,

HashTable ht = { (1, 1), (2, 1), (3, 1) }

Now, I implement it like, Integer foo = Integer(1) and declare hash table like,

HashTable ht = { (foo, foo), (2, foo), (3, foo) }

Now, as per I understood from this, it will reduce heap space used by JVM. Is this correct ? Another point is that, in C, I usually use structure like,

HashTable ht = { (1, mem), (2, mem), (3, mem) } 
{ where mem is memory location (say 10) of 1 }

And then use the location to access the value. Now, if mem value is less than Int (say Byte), I can save space. However, I don't understand how to implement this in Java. Or is there any other way to reduce space of the hash table ? (means by reducing repeatedly storing same object in Java's way).

回答1:

The most space-efficient way with Integers is to use Integer.valueOf(), which uses the flyweight design pattern to reduce the memory usage for small values. Values between -128 and (usually) 127 need no additional memory.