用Java初始化Map,Hashmap

你将如何初始化Java中的静态地图?

方法一:如下创建一个从Hashmap扩展的类

下面是一个例子,说明我使用CustomMap的方式:


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"));
  }
}
链接地址: http://www.djcxy.com/p/18023.html

上一篇: initialize a Map, Hashmap, in Java

下一篇: How to delete items from a dictionary while iterating over it?