2016-04-30 123 views
0

如何初始化Java中的靜態Map?用Java初始化Map,Hashmap

方法一:創建一個類從哈希映射延長如下

這裏有一個例子說明使用CustomMap的方式我做:

+0

這是你在找什麼? http://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way –

+0

@Vishal: - FYI-找到的解決方案,它在那裏作爲答案 –

+1

可能的重複[我如何初始化靜態映射?](http://stackoverflow.com/questions/507602/how-can-i-initialize-a-static-map) –

回答

0
public class CustomMap < K, V > extends java.util.HashMap < K, V > { 

    public CustomMap(Object[]...objs) { 
    super(); 
    this.of(objs); 
    } 

    public java.util.Map < K, V > of(Object[]...objs) { 
    for (Object[] o: objs) { 
     this.of((K) o[0], (V) o[1]); 
    } 
    return this; 
    } 

    public java.util.Map < K, V > of(K k, V v) { 
    this.put(k, v); 
    return this; 
    } 

    public static Object[] tuple(Object k, Object v) { 
    return new Object[] { 
     k, v 
    }; 
    } 

    //USAGE 
    public static void main(String...args) { 
    //import static CustomMap.tuple; 
    java.util.Map < String, String > cmap = new CustomMap < > (CustomMap.tuple("One", "Two")); 
    } 
}