Before I discovered the new writing method in Java, I always initialized List and Map like this:
//初始化List Listlist = new ArrayList (); list.add("m.sbmmt.com"); list.add("string2"); //some other list.add() code...... list.add("stringN"); //初始化Map Map map = new HashMap (); map.put("key1", "value1"); map.put("key2", "value2"); //.... some other map.put() code map.put("keyN", "valueN");
It’s so troublesome. . . . . One day I came across such a method:
//初始化List Listlist = new ArrayList (){{ add("string1"); add("string2"); //some other add() code...... add("stringN"); }}; //初始化Map Map map = new HashMap (){{ put("key1", "value1"); put("key2", "php.cn"); //.... some other put() code put("keyN", "valueN"); }};
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:
rrayListlist = 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(){{ 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!