3

I have a a 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.

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

How do i do this?

4

2 回答 2

9

You can either use Arrays.asList():

getObjects(Arrays.asList(a));

or Collections.singletonList() if you have only one value (faster and more compact):

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));
于 2012-06-28T06:50:15.683 回答
2

This is how you would pass it.

getObjects(Arrays.asList(a)).

Java Reference for Arrays.asList()

于 2012-06-28T06:46:35.360 回答