X Tutup
Skip to content

HashMap的几种初始化方法 #2

@Sitrone

Description

@Sitrone

ArrayList初始化方法

  1. 常规方法
List<string> list = new ArrayList</string><string>();  
list.add("string1");  
list.add("string2");  
//some other list.add() code......  
list.add("stringN");
  1. 使用Arrrays.asList()方法
ArrayList<String> list = new ArrayList(Arrays.asList("Tom", "Jerry", "Mike"));  
  1. 使用双括号
List list = new ArrayList<String>(){{  
    add("A");  
    add("B");  
}};

HashMap初始化

非static HashMap

  1. 最简单直观的
        Map<String, Integer>  myMap = new HashMap<String, Integer>();
        myMap.put("Li Lei", 1);
        myMap.put("Han Meimei", 2);

但是初始化数据多的时候,这样写会很麻烦,有没有更好的办法呢?

  1. 双括号,匿名内部类初始化HashMap
    Map<String, Integer> myMap = new HashMap<String, Integer>() {
            {
                put("key1","value1");
                put("key2","value2");
            }
        };

初始化immutable HashMap

  1. 同上
  2. 双括号
public static final HashMap hm = new HashMap(){
{
   put("key1","value1");
   put("key2","value2");
}
};  

上面的代码包含了两个隐藏的东西:
* 一个匿名内部类
* 一个实例块

可以对上面的代码进行拆解

  • 拆除匿名内部类
private static class MyHashMap() extends HashMap
{
    {
       put("key1","value1");
       put("key2","value2");
    }
}
public static final HashMap hm = new MyHashMap();
  • 拆除代码块
private static class MyHashMap() extends HashMap
{
    public MyHashMap()
    {
       this.put("key1","value1");  // <-- added 'this'
       this.put("key2","value2");  // <-- added 'this'
    }
}
public static final HashMap hm = new MyHashMap();  

immutable HashMap初始化推荐的方法:

public class Test {
    private static final Map<Integer, String> MY_MAP = createMap();

    private static Map<Integer, String> createMap() {
        Map<Integer, String> result = new HashMap<Integer, String>();
        result.put(1, "one");
        result.put(2, "two");
        return Collections.unmodifiableMap(result);
    }
}

或者是用Google提供的Guava

static final Map<Integer, String> MY_MAP = ImmutableMap.of(
    1, "one",
    2, "two"
);

双括号的方式不推荐使用
原因是:

  1. 匿名内部类的声明方式,所以引用中持有着外部类的引用。所以当时串行化这个集合时外部类也会被不知不觉的串行化,当外部类没有实现serialize接口时,就会报错。
  2. 这种方式其实是声明了一个继承自HashMap的子类。然而有些串行化方法,例如要通过Gson串行化为json,或者要串行化为xml时,类库中提供的方式,是无法串行化Hashset或者HashMap的子类的,从而导致串行化失败。

参考链接

使用双括号初始化可能出现的问题

  1. http://www.c2.com/cgi/wiki?DoubleBraceInitialization
  2. http://stackoverflow.com/questions/6802483/how-to-directly-initialize-a-hashmap-in-a-literal-way

具体的例子

  1. HashMap Construction with initial values
  2. 聊聊 Java 中 HashMap 初始化的另一种方式
  3. Java的大括号语法糖

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup