可以在用户定义的构造函数内填充一个 List 吗?

huangapple go评论75阅读模式
英文:

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&lt;Integer&gt; arrays within a user defined constructor.

for example:

import java.util.*;

public class Sample {

	// variables
	private List&lt;Integer&gt; myList = new ArrayList&lt;&gt;(); 
	
	// constructor
	// list of values something like (1,2,3,4,5)
	public Sample(List&lt;Integer&gt; 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);

另请参阅:Java中的Varargs | Baeldung

英文:

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&lt;Integer&gt; 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);

huangapple
  • 本文由 发表于 2020年9月23日 01:15:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64014646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定