Home > Java > javaTutorial > 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

黄舟
Release: 2018-05-15 15:12:17
Original
4088 people have browsed it

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");
Copy after login
Map<String,String> sMap = new HashMap<String, String>(); 
sMap.put("k1", "v1"); 
sMap.put("k2", "v2");
Copy after login

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,是不支持添加或删除元素的
Copy after login
private Map<Integer, String> newsEventMap = new HashMap<Integer, String>(){{ 
put("k1","v1"); 
put("k2","v2"); 
}};
Copy after login

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!

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