Class SimpleMap<K,V>
- Type Parameters:
K- The key type.V- The value type.
- All Implemented Interfaces:
Map<K,V>
This class provides a simple, efficient, immutable map implementation for scenarios where the
set of keys and values is known in advance and doesn't need to change. It's particularly useful
for small maps (typically less than 10 entries) where the overhead of a HashMap is not
justified.
Features:
- Unmodifiable: All mutation operations throw
UnsupportedOperationException - Fixed Keys and Values: Keys and values are set at construction time
- Insertion Order: Preserves the order of keys as provided in the constructor
- Null Support: Supports null keys and values (unlike
Map.of()) - Array-Backed: Uses simple arrays for storage, avoiding hash computation overhead
- Memory Efficient: Minimal memory footprint compared to
HashMap - Predictable Performance: O(n) lookup time, but faster than
HashMapfor small n
Use Cases:
- Immutable configuration maps with a fixed set of known keys
- Small lookup tables that should not be modified
- Method return values where immutability is desired
- Situations where map size is small and keys are known at compile time
Usage:
Restrictions:
- Immutable: Cannot add, remove, or modify entries after construction
- Fixed Size: Size is determined at construction time
- Unique Keys: Keys must be unique (no duplicates)
- Array Length: Keys and values arrays must have the same length
Performance Characteristics:
- get(key): O(n) - Linear search through keys array
- size(): O(1) - Direct array length access
- Memory: Lower overhead than
HashMapfor small maps
Thread Safety:
This class is thread-safe since it's immutable after construction. Multiple threads can safely read from a SimpleMap concurrently without synchronization.
Example - Configuration Map:
Comparison with Map.of():
- Null Support: SimpleMap supports null keys/values, Map.of() does not
- Insertion Order: SimpleMap preserves insertion order, Map.of() does not
- Size Limit: Map.of() limited to 10 entries, SimpleMap has no limit
See Also:
SimpleMap- The modifiable version of this class- Overview > juneau-commons
-
Nested Class Summary
Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K extends Object,V extends Object>, AbstractMap.SimpleImmutableEntry<K extends Object, V extends Object> -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionentrySet()Returns aSetview of the mappings contained in this map.booleanCompares the specified object with this map for equality.Returns the value associated with the specified key.inthashCode()Returns the hash code value for this map.keySet()Returns aSetview of the keys contained in this map.ThrowsUnsupportedOperationExceptionas this map is unmodifiable.toString()Returns a string representation of this map.Methods inherited from class java.util.AbstractMap
clear, clone, containsKey, containsValue, isEmpty, putAll, remove, size, valuesMethods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, waitMethods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, remove, replace, replace, replaceAll
-
Constructor Details
-
SimpleMap
Constructs a new SimpleMap with the specified keys and values.The keys and values arrays are stored by reference (not copied), so external modifications to the arrays after construction will affect the map's behavior. For true immutability, ensure the arrays are not modified after passing them to this constructor.
Example:
String[]
keys = {"name" ,"age" ,"city" }; Object[]values = {"John" , 30,"NYC" }; SimpleMap<String,Object>person =new SimpleMap<>(keys ,values );- Parameters:
keys- The map keys. Must not benull . Individual keys can benull .values- The map values. Must not benull and must have the same length as keys. Individual values can benull .- Throws:
IllegalArgumentException- if:- The keys array is
null - The values array is
null - The keys and values arrays have different lengths
- Any key appears more than once (duplicate keys)
- The keys array is
-
-
Method Details
-
entrySet
Returns aSetview of the mappings contained in this map.The returned set is unmodifiable and backed by the underlying entries array.
Example:
SimpleMap<String,Integer>
map =new SimpleMap<>(new String[]{"a" ,"b" },new Integer[]{1, 2} );for (Map.Entry<String,Integer>entry :map .entrySet()) { System.out .println(entry .getKey() +"=" +entry .getValue()); } -
get
Returns the value associated with the specified key.This method performs a linear search through the keys array, using
Object.equals(Object)for comparison. For small maps (typically less than 10 entries), this is often faster than the hash lookup inHashMap.Example:
SimpleMap<String,Integer>
map =new SimpleMap<>(new String[]{"age" ,"score" },new Integer[]{25, 100} ); Integerage =map .get("age" );// Returns: 25 Integerheight =map .get("height" );// Returns: null (key not found) -
keySet
Returns aSetview of the keys contained in this map.The returned set is unmodifiable and backed by the underlying keys array.
Example:
SimpleMap<String,Integer>
map =new SimpleMap<>(new String[]{"x" ,"y" ,"z" },new Integer[]{1, 2, 3} ); Set<String>keys =map .keySet();// Returns: [x, y, z] -
put
ThrowsUnsupportedOperationExceptionas this map is unmodifiable.- Specified by:
putin interfaceMap<K,V> - Overrides:
putin classAbstractMap<K,V> - Parameters:
key- Ignored.value- Ignored.- Returns:
- Never returns normally.
- Throws:
UnsupportedOperationException- Always thrown, as this map cannot be modified.
-
toString
Returns a string representation of this map.The format follows the standard Java map convention:
"{key1=value1, key2=value2, ...}" - Overrides:
toStringin classAbstractMap<K,V> - Returns:
- A string representation of this map.
-
equals
Compares the specified object with this map for equality.Returns
true if the given object is also a map and the two maps represent the same mappings. More formally, two mapsm1 andm2 represent the same mappings ifm1.entrySet().equals(m2.entrySet()) .This implementation compares the entry sets of the two maps.
-
hashCode
Returns the hash code value for this map.The hash code of a map is defined to be the sum of the hash codes of each entry in the map's
entrySet() view. This ensures thatm1.equals(m2) implies thatm1.hashCode()==m2.hashCode() for any two mapsm1 andm2 , as required by the general contract ofObject.hashCode().This implementation computes the hash code from the entry set.
-