注意:这个答案实际上属于问题
如何以字面量方式直接初始化HashMap?,但由于在撰写本文时该问题被标记为重复项...
在Java 9之前,使用
Map.of()(也仅限于10个映射)之前,您可以扩展自己选择的
Map
实现,例如:
public class InitHashMap<K, V> extends HashMap<K, V>
重新实现HashMap的构造函数:
:
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 );
}
并添加一个额外的构造函数,受Aerthel's answer启发,但使用Object...
和<K, V>
类型是通用的:
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 );
}
}
运行
public static void main( final String[] args ) {
final Map<Integer, String> map = new InitHashMap<>( 1, "First", 2, "Second", 3, "Third" );
System.out.println( map );
}
输出
{1=First, 2=Second, 3=Third}
您也可以同样扩展
Map
接口:
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:
if ( keyOrValue == null )
throw new IllegalArgumentException( "Key[" + (i >>> 1) + "] is <null>." );
key = (K) keyOrValue;
continue;
case 1:
map.put( key, (V) keyOrValue );
}
return map;
}
}
运行
public static void main( final String[] args ) {
System.out.println( InitMap.of( 1, "First", 2, "Second", 3, "Third" ) );
}
输出
{1=First, 2=Second, 3=Third}
Map.of
,否则请使用Map.ofEntries
,请参见https://dev59.com/1nRB5IYBdhLWcg3wyqOo#37384773。 - akhil_mittal