英文:
Can you populate a List<Integer> within a user defined constructor?
问题
我刚接触Java,希望能得到关于在用户定义的构造函数内实例化 `List<Integer>` 数组的一些建议。
例如:
import java.util.*;
public class Sample {
// 变量
private List<Integer> myList = new ArrayList<>();
// 构造函数
// 值的列表,类似于 (1,2,3,4,5)
public Sample(List<Integer> listOfValues)
{
{
myList.addAll(Arrays.asList( listOfValues ));
}
}
}
所以我的构造函数调用将会是:
Sample s = new Sample(Arrays.asList(1, 2, 3, 4, 5));
是否可能像上面那样做,或者是否有其他方法来完成这种类型的赋值?
英文:
I'm new to Java and hoping for some advice on instantiating List<Integer>
arrays within a user defined constructor.
for example:
import java.util.*;
public class Sample {
// variables
private List<Integer> myList = new ArrayList<>();
// constructor
// list of values something like (1,2,3,4,5)
public Sample(List<Integer> listOfValues)
{
{
myListArrays.addAll(Arrays.asList( listOfValues ));
}
}
}
So my constructor call would be:
Sample s = new Sample((1,2,3,4,5));
Is it possible to do something like the above or is there an alternative approach to this type of assignment?
答案1
得分: 5
如果您想进行类似的调用,那么您需要使用varargs。
public Sample(Integer... listOfValues)
{
myListArrays.addAll(Arrays.asList(listOfValues));
}
Sample s = new Sample(1,2,3,4,5);
英文:
If you want to make a call like that, then you need to use varargs.
public Sample(Integer... listOfValues)
{
myListArrays.addAll(Arrays.asList(listOfValues));
}
Sample s = new Sample(1,2,3,4,5);
See also: Varargs in Java | Baeldung
答案2
得分: 0
声明但不实例化
任务是在构造函数中实例化它,因此您无需在声明时实例化它:
private List<Integer> myList;
可以向构造函数传递参数
public Sample(Integer[] values) {
myList = Arrays.asList(values);
}
调用它
Integer[] elements = {1, 2, 3, 4, 5, 6};
Sample mySample = new Sample(elements);
英文:
Declare without instantiating
The task is to instantiate it in the constructor, therefore you do not need to instantiate it at declaration:
private List<Integer> myList;
You can pass a parameter to the constructor
public Sample(Integer[] values) {
myList = Arrays.asList(values)
}
Call it
Integer[] elements = {1, 2, 3, 4, 5, 6};
Sample mySample = new Sample(elements);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论