Java Reference
In-Depth Information
}
}
value in the weak hashmap, and then removes the key's strong reference by assigning
null
to
lo
.
main()
next enters a while loop that executes until the map is empty
(
map.isEmpty()
returns true).
Each loop iteration begins with a
System.gc()
method call, which may or may
notcauseagarbagecollectiontotakeplace(dependinguponplatform).Toencouragea
garbagecollection,theiterationthencreatesa
LargeObject
objectandthrowsaway
itsreference.Thisactivityshouldeventuallycausethegarbagecollectortorunandre-
move the map's solitary entry.
When I run this application on my Windows XP platform, I observe the following
output—youmightneedtomodifythecodeifyoufindthattheapplicationisinanin-
finite loop:
{LargeObject@5224ee=Large Object}
{}
Note
WeakHashMap
is useful for avoiding memory leaks, as explained in Brian
Goetz'sarticle“JavaTheoryandPractice:PluggingMemoryLeakswithWeakRefer-
p11225/
).
EnumMap
The
EnumMap
class provides a
Map
implementation whose keys are the members of
the same enum. Null keys are not permitted; any attempt to store a null key results in
athrown
NullPointerException
.Becauseanenummapisrepresentedinternally
as an array, an enum map approaches an array in terms of performance.
EnumMap
supplies the following constructors:
•
EnumMap(Class<K> keyType)
createsanemptyenummapwiththespe-
cified
keyType
. This constructor throws
NullPointerException
when
keyType
contains the null reference.
•
EnumMap(EnumMap<K,? extends V> m)
createsanenummapwiththe
samekeytypeas
m
,andwith
m
'sentries.Thisconstructorthrows
NullPoint-
erException
when
m
contains the null reference.