Arvind Sridharan
Arvind Sridharan

Reputation: 4065

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

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?

Upvotes: 3

Views: 2580

Answers (2)

Arvind Sridharan
Arvind Sridharan

Reputation: 4065

This is how you would pass it.

getObjects(Arrays.asList(a)).

Java Reference for Arrays.asList()

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340993

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));

Upvotes: 9

Related Questions