Home  >  Article  >  Java  >  Some writing methods for List and Map initialization in Java

Some writing methods for List and Map initialization in Java

高洛峰
高洛峰Original
2017-01-22 16:04:301705browse

Before I discovered the new writing method in Java, I always initialized List and Map like this:

//初始化List
    List<string> list = new ArrayList</string><string>();
    list.add("www.php.cn");
    list.add("string2");
    //some other list.add() code......
    list.add("stringN");

    //初始化Map
    Map</string><string , String> map = new HashMap</string><string , String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    //.... some other map.put() code
    map.put("keyN", "valueN");
    </string>

It’s so troublesome. . . . . One day I came across such a method:

//初始化List
    List<string> list = new ArrayList</string><string>(){{
    add("string1");
    add("string2");
    //some other add() code......
    add("stringN");
    }};

    //初始化Map
    Map</string><string , String> map = new HashMap</string><string , String>(){{
    put("key1", "value1");
    put("key2", "php.cn");
    //.... some other put() code
    put("keyN", "valueN");
    }};
    </string>

Although it seems that I haven’t written much less code, I personally feel that this method is much simpler and smoother haha~
Example, now Yiju editor tested two examples of List to make it simpler

Method one:
Use the mutual conversion method between Array and ArrayList, the code is as follows:

rrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));

Method two:
Use The add method of ArrayList completes the initialization assignment. The code is as follows:

List list = new ArrayList<String>(){{
add("A");
add("B");
}}

For more articles related to some writing methods of List and Map initialization in Java, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn