Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 88d8807

Browse filesBrowse files
committed
如何通过一行代码初始化ArrayList
1 parent 6367396 commit 88d8807
Copy full SHA for 88d8807

File tree

Expand file treeCollapse file tree

2 files changed

+57
-0
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+57
-0
lines changed

‎README.md

Copy file name to clipboardExpand all lines: README.md
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ stackoverflow-Java-top-qa
3434
3535
* [去掉烦人的“!=null"(判空语句](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/avoiding-null-statements-in-java.md)
3636
* [获取完整的堆栈信息](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/get-current-stack-trace-in-java.md)
37+
* [如何通过一行代码初始化ArrayList](https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/initialization-of-an-arraylist-in-one-line.md)
3738

3839
> 网络
3940
+56Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
##如何通过一行代码初始化ArrayList
2+
3+
###问题
4+
为了测试,我需要临时快速创建一个list。一开始我这样做:
5+
```java
6+
ArrayList<String> places = new ArrayList<String>();
7+
places.add("Buenos Aires");
8+
places.add("Córdoba");
9+
places.add("La Plata");
10+
```
11+
之后我重构了下
12+
```java
13+
ArrayList<String> places = new ArrayList<String>(
14+
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
15+
```
16+
是否有更加简便的方法呢?
17+
18+
###回答
19+
20+
####常见方式
21+
实际上,也许“最好”的方式,就是你写的这个方式,因为它不用再创建新的`List`:
22+
```
23+
ArrayList<String> list = new ArrayList<String>();
24+
list.add("A");
25+
list.add("B");
26+
list.add("C");
27+
```
28+
只是这个方式看上去要多写些代码,让人郁闷
29+
30+
####匿名内部类
31+
当然,还有其他方式,例如,写一个匿名内部类,然后在其中做初始化(也被称为 brace initialization):
32+
```
33+
ArrayList<String> list = new ArrayList<String>() {{
34+
add("A");
35+
add("B");
36+
add("C");
37+
}};
38+
```
39+
但是,我不喜欢这个方式。只是为了做个初始化,却要在`ArrayList`的同一行后面加这么一坨代码。
40+
41+
####Arrays.asList
42+
```
43+
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
44+
```
45+
####Collections.singletonList
46+
```
47+
List<String> places = Collections.singletonList("Buenos Aires");
48+
```
49+
注意:后面的这两种方式,得到的是一个定长的`List`(如果add操作会抛异常)。如果你需要一个不定长的`List`,可以这样做:
50+
```
51+
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
52+
53+
```
54+
55+
stackoverflow链接:
56+
http://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.