Reputation: 4065
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
Reputation: 4065
This is how you would pass it.
getObjects(Arrays.asList(a)).
Java Reference for Arrays.asList()
Upvotes: 2
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