initialize a Map, Hashmap, in Java

我怕爱的太早我们不能终老 提交于 2019-12-12 03:26:19

问题


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:


回答1:


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"));
  }
}


来源:https://stackoverflow.com/questions/36951414/initialize-a-map-hashmap-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!