Home  >  Article  >  Java  >  How to quickly create instances of List and Map with initial values ​​in Java

How to quickly create instances of List and Map with initial values ​​in Java

黄舟
黄舟Original
2018-05-15 15:12:174019browse

The following editor will bring you an article to quickly create List and Map instances with initial values ​​in java. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

The way to initialize a List and Map object and add values ​​is as follows:

List<String> sList = new ArrayList<String>(); 
sList.add("str1"); 
sList.add("str2");
Map<String,String> sMap = new HashMap<String, String>(); 
sMap.put("k1", "v1"); 
sMap.put("k2", "v2");

This operation can also be implemented with the following code, which can make the code look like Neater:

List<String> sList = Arrays.asList("str1", "str2");//这种方法生成的list,是不支持添加或删除元素的
private Map<Integer, String> newsEventMap = new HashMap<Integer, String>(){{ 
put("k1","v1"); 
put("k2","v2"); 
}};

The above is the detailed content of How to quickly create instances of List and Map with initial values ​​in Java. For more information, please follow other related articles on 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