简体   繁体   English

如何动态构建列表并将其作为方法参数传递?

[英]How do I Construct a list on the fly and pass it as a method parameter?

I have aa method like this : 我有一个像这样的方法:

List < Object > getObjects(List<Integer> ids)

I want to construct a list on the fly (as a parameter) using an integer (say some int a) instead of creating and storing a list in a local variable and then passing it. 我想使用整数(比如一些int a)动态构建一个列表(作为参数),而不是在局部变量中创建和存储列表然后传递它。

List<Integer> intList = new ArrayList<Integer>();
intList.add(a);
getObjects(intList)

How do i do this? 我该怎么做呢?

You can either use Arrays.asList() : 您可以使用Arrays.asList()

getObjects(Arrays.asList(a));

or Collections.singletonList() if you have only one value (faster and more compact): 或者Collections.singletonList()如果你只有一个值(更快,更紧凑):

getObjects(Collections.singletonList(a));

Tip: consider static imports: 提示:考虑静态导入:

import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;

getObjects(asList(a));
getObjects(singletonList(a));

This is how you would pass it. 这就是你传递它的方式。

getObjects(Arrays.asList(a)).

Java Reference for Arrays.asList() Arrays.asList()的Java参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM