Java 使用一些预定义的值初始化 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16194921/
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
Initializing ArrayList with some predefined values
提问by Pawan
I have an sample program as shown.
我有一个示例程序,如图所示。
I want my ArrayList
symbolsPresent
to be initialized with some predefined symbols: ONE, TWO, THREE, and FOUR.
我希望ArrayList
symbolsPresent
用一些预定义的符号初始化我:一、二、三和四。
symbolsPresent.add("ONE");
symbolsPresent.add("TWO");
symbolsPresent.add("THREE");
symbolsPresent.add("FOUR");
import java.util.ArrayList;
public class Test {
private ArrayList<String> symbolsPresent = new ArrayList<String>();
public ArrayList<String> getSymbolsPresent() {
return symbolsPresent;
}
public void setSymbolsPresent(ArrayList<String> symbolsPresent) {
this.symbolsPresent = symbolsPresent;
}
public static void main(String args[]) {
Test t = new Test();
System.out.println("Symbols Present is" + t.symbolsPresent);
}
}
Is that possible?
那可能吗?
回答by PermGenError
How about using overloaded ArrayList constructor.
如何使用重载的 ArrayList 构造函数。
private ArrayList<String> symbolsPresent = new ArrayList<String>(Arrays.asList(new String[] {"One","Two","Three","Four"}));
回答by samba
回答by mki
Personnaly I like to do all the initialisations in the constructor
我个人喜欢在构造函数中进行所有的初始化
public Test()
{
symbolsPresent = new ArrayList<String>();
symbolsPresent.add("ONE");
symbolsPresent.add("TWO");
symbolsPresent.add("THREE");
symbolsPresent.add("FOUR");
}
Edit : It is a choice of course and others prefer to initialize in the declaration. Both are valid, I have choosen the constructor because all type of initialitions are possible there (if you need a loop or parameters, ...). However I initialize the constants in the declaration on the top on the source.
The most important is to follow a rule that you like and be consistent in our classes.
编辑:这当然是一个选择,其他人更喜欢在声明中初始化。两者都是有效的,我选择了构造函数,因为那里可以进行所有类型的初始化(如果您需要循环或参数,...)。但是,我在源代码顶部的声明中初始化了常量。
最重要的是遵循您喜欢的规则并在我们的课程中保持一致。
回答by Reimeus
Double brace initialization is an option:
双括号初始化是一个选项:
List<String> symbolsPresent = new ArrayList<String>() {{
add("ONE");
add("TWO");
add("THREE");
add("FOUR");
}};
Note that the String
generic type argument isnecessary in the assigned expression as indicated by JLS §15.9
注意,String
通用类型参数是通过所指示的所分配的表达必要JLS§15.9
It is a compile-time error if a class instance creation expression declares an anonymous class using the "<>" form for the class's type arguments.
如果类实例创建表达式使用“<>”形式为类的类型参数声明匿名类,则会出现编译时错误。
回答by ZachF
Also, if you want to enforce the List to be read-only (throws a UnsupportedOperationException if modified):
此外,如果您想强制 List 为只读(如果修改则抛出 UnsupportedOperationException):
List<String> places = Collections.unmodifiableList(Arrays.asList("One", "Two", "Three"));
List<String> places = Collections.unmodifiableList(Arrays.asList("One", "Two", "Three"));
回答by Dilum Ranatunga
You can also use the varargs syntax to make your code cleaner:
您还可以使用 varargs 语法使您的代码更简洁:
Use the overloaded constructor:
使用重载的构造函数:
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c"));
Subclass ArrayList in a utils module:
utils 模块中的 ArrayList 子类:
public class MyArrayList<T> extends ArrayList<T> {
public MyArrayList(T... values) {
super(Arrays.asList(values));
}
}
ArrayList<String> list = new MyArrayList<String>("a", "b", "c");
Or have a static factory method (my preferred approach):
或者有一个静态工厂方法(我的首选方法):
public class Utils {
public static <T> ArrayList<T> asArrayList(T... values) {
return new ArrayList<T>(Arrays.asList(values));
}
}
ArrayList<String> list = Utils.asArrayList("a", "b", "c");
回答by Manoj Kumar
I would suggest to use Arrays.asList() for single line initialization. For different ways of declaring and initializing a List you can also refer Initialization of ArrayList in Java
我建议使用 Arrays.asList() 进行单行初始化。对于声明和初始化 List 的不同方式,您还可以参考Java 中的 ArrayList 初始化
回答by Domenico Vacchiano
I use a generic class that inherit from ArrayList and implement a constructor with a parameter with variable number or arguments :
我使用从 ArrayList 继承的泛型类,并使用带有可变编号或参数的参数实现构造函数:
public class MyArrayList<T> extends ArrayList<T> {
public MyArrayList(T...items){
for (T item : items) {
this.add(item);
}
}
}
Example:
例子:
MyArrayList<String>myArrayList=new MyArrayList<String>("s1","s2","s2");
回答by Kristy Hughes
import com.google.common.collect.Lists;
...
ArrayList<String> getSymbolsPresent = Lists.newArrayList("item 1", "item 2");
...
回答by George Siggouroglou
You can use Java 8 Stream API.
You can create a Stream of objects and collect them as a List.
您可以使用Java 8 Stream API。
您可以创建一个对象流并将它们收集为一个列表。
private List<String> symbolsPresent = Stream.of("ONE", "TWO", "THREE", "FOUR")
.collect(Collectors.toList());