Java 初始化一个 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4213151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialising An ArrayList
提问by sark9012
Very simple question, I think. How do I initialise an ArrayListcalled time.
很简单的问题,我想。我如何初始化一个ArrayList被调用的time.
Thanks.
谢谢。
采纳答案by aioobe
This depends on what you mean by initialize. To simply initialize the variable timewith the value of a reference to a new ArrayList, you do
这取决于您所说的initialize是什么意思。要简单地使用对timenew 的引用值初始化变量ArrayList,您可以
ArrayList<String> time = new ArrayList<String>();
(replace Stringwith the type of the objects you want to store in the list.)
(替换String为您要存储在列表中的对象的类型。)
If you want to put stuff in the list, you could do
如果你想把东西放在列表中,你可以这样做
ArrayList<String> time = new ArrayList<String>();
time.add("hello");
time.add("there");
time.add("world");
You could also do
你也可以这样做
ArrayList<String> time = new ArrayList<String>(
Arrays.asList("hello", "there", "world"));
or by using an instance initializer
或通过使用实例初始值设定项
ArrayList<String> time = new ArrayList<String>() {{
add("hello");
add("there");
add("world");
}};
回答by Jigar Joshi
< 1.5 jdk
< 1.5 jdk
List time = new ArrayList();
gt or eq 1.5 jdk
gt 或 eq 1.5 jdk
List<T> time = new ArrayList<T>();
回答by Vincent Robert
Arrays.asListallows you to build a Listfrom a list of values.
Arrays.asList允许您List从值列表中构建一个。
You can then build your ArrayListby passing it the read-only list generated by Arrays.asList.
然后,您可以ArrayList通过将生成的只读列表传递给它来构建您的Arrays.asList。
ArrayList time = new ArrayList(Arrays.asList("a", "b", "c"));
But if all you need is a Listdeclared inline, just go with Arrays.asListalone.
但是如果你只需要一个List声明的内联,就Arrays.asList单独使用。
List time = Arrays.asList("a", "b", "c");
回答by asela38
ArrayList<String> time = ArrayList.class.newInstance();
回答by missingfaktor
Alternative:
选择:
Using Google Collections, you could write:
使用 Google Collections,您可以编写:
import com.google.collect.Lists.*;
List<String> time = newArrayList();
You could even specify the initial contents of Listas follows:
你甚至可以指定List如下的初始内容:
List<String> time = newArrayList("a", "b", "c");

