Note: This answer actually belongs to question How to directly initialize a HashMap (in a literal way)? but since that was marked as duplicate of this one at time of this writing...
Prior to Java 9 with its Map.of() (which is also limited to 10 mappings) you can extend a Map
implementation of your choice, e.g.:
public class InitHashMap<K, V> extends HashMap<K, V>
re-implement HashMap
's constructors:
public InitHashMap() {
super();
}
public InitHashMap( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
}
public InitHashMap( int initialCapacity ) {
super( initialCapacity );
}
public InitHashMap( Map<? extends K, ? extends V> map ) {
super( map );
}
and add an additional constructor that's inspired by Aerthel's answer but is generic by using Object...
and <K, V>
types:
public InitHashMap( final Object... keyValuePairs ) {
if ( keyValuePairs.length % 2 != 0 )
throw new IllegalArgumentException( "Uneven number of arguments." );
K key = null;
int i = -1;
for ( final Object keyOrValue : keyValuePairs )
switch ( ++i % 2 ) {
case 0: // key
if ( keyOrValue == null )
throw new IllegalArgumentException( "Key[" + (i >>> 1) + "] is <null>." );
key = (K) keyOrValue;
continue;
case 1: // value
put( key, (V) keyOrValue );
}
}
Run
public static void main( final String[] args ) {
final Map<Integer, String> map = new InitHashMap<>( 1, "First", 2, "Second", 3, "Third" );
System.out.println( map );
}
Output
{1=First, 2=Second, 3=Third}
You also can extend the Map
interface likewise:
public interface InitMap<K, V> extends Map<K, V> {
static <K, V> Map<K, V> of( final Object... keyValuePairs ) {
if ( keyValuePairs.length % 2 != 0 )
throw new IllegalArgumentException( "Uneven number of arguments." );
final Map<K, V> map = new HashMap<>( keyValuePairs.length >>> 1, .75f );
K key = null;
int i = -1;
for ( final Object keyOrValue : keyValuePairs )
switch ( ++i % 2 ) {
case 0: // key
if ( keyOrValue == null )
throw new IllegalArgumentException( "Key[" + (i >>> 1) + "] is <null>." );
key = (K) keyOrValue;
continue;
case 1: // value
map.put( key, (V) keyOrValue );
}
return map;
}
}
Run
public static void main( final String[] args ) {
System.out.println( InitMap.of( 1, "First", 2, "Second", 3, "Third" ) );
}
Output
{1=First, 2=Second, 3=Third}
Map.of
elseMap.ofEntries
, check https://mcmap.net/q/45459/-how-can-i-initialise-a-static-map – Hertford