A List in Java is Shared with some way of initializing a Map

  • 2020-04-01 02:41:11
  • OfStack

Before I found a new way to write Java, I always initialized List and Map like this:


//Initialize a List
    List<string> list = new ArrayList</string><string>();
    list.add("www.jb51.net");
    list.add("string2");
    //some other list.add() code......
    list.add("stringN");

    //To initialize the 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>

That's a lot of trouble... One day lu to such a way:


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

    //To initialize the Map
    Map</string><string , String> map = new HashMap</string><string , String>(){{
    put("key1", "value1");
    put("key2", "jb51.net");
    //.... some other put() code
    put("keyN", "valueN");
    }};
    </string>

Although it doesn't seem like much less code, I think this approach is much more concise, very smooth
For example, it is simpler to test the List two instances at this site later

Method one:
Using the mutual conversion method of Array and ArrayList, the code is as follows:


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

Method 2:
Use the add method of ArrayList to complete the initialization assignment. The code is as follows:


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


Related articles: