initialize a Map, Hashmap, in Java

How would you initialise a static Map in Java?

Method one: Create a Class extend from Hashmap as below

Here is an example illustrating the way i did using a 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/18024.html

上一篇: O集成框架实现的摘要?

下一篇: 用Java初始化Map,Hashmap