Before Java discovered new writing methods, I always initialized List and Map like this:
Copy the code code as follows:
//Initialize List
List<string> list = new ArrayList</string><string>();
list.add("www.VeVB.COm");
list.add("string2");
//some other list.add() code......
list.add("stringN");
//Initialize 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>
What a hassle. . . . . One day I came across a method like this:
Copy the code code as follows:
//Initialize List
List<string> list = new ArrayList</string><string>(){{
add("string1");
add("string2");
//some other add() code......
add("stringN");
}};
//Initialize Map
Map</string><string , String> map = new HashMap</string><string , String>(){{
put("key1", "value1");
put("key2", "VeVB.COm");
//.... 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~
For example, Yiju editor tested two examples of List which are simpler.
Method one:
Using the mutual conversion method between Array and ArrayList, the code is as follows:
Copy the code code as follows:
rrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));
Method two:
Use the add method of ArrayList to complete the initialization assignment. The code is as follows:
Copy the code code as follows:
List list = new ArrayList<String>(){{
add("A");
add("B");
}}