Home > Java > javaTutorial > body text

Some writing methods for List and Map initialization in Java

高洛峰
Release: 2017-01-22 16:04:30
Original
1639 people have browsed it

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>
Copy after login

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>
Copy after login

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"));
Copy after login

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!