30
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Map 初期化

30
Posted at
InitializeMapSample.java
import java.util.Map;
import java.util.HashMap;
class InitializeMapSample {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>() {
            {put("foo", "fooVal");}
            {put("bar", "barVal");}
        };
        System.out.println(map.get("foo"));  
        System.out.println(map.get("bar"));  
    }
}

このコードよくわからなかったのだけど、
http://www.coderanch.com/t/386333/java/java/HashMap-Construction-initial-values
で解説されていた。
匿名クラスと初期化ブロックを使っている。
つまり、HashMap を継承したクラスを作って、初期化ブロックを定義している。
もちろん初期化ブロックをひとつにまとめてもよい。

new HashMap<String, String>() {
    {
        put("foo", "fooVal");
        put("bar", "barVal");
    }
};
30
32
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?