One-liner to make a read-only list of N copies of a link in Java

I have a link to Callable<V>

, and I want to put it in a list N times to go to ExecutorService.invokeAll(...)

. Is there one liner to accomplish this:

ArrayList<Callable<V>> list = new ArrayList<>(N);
for (int k = 0; k < N; ++k) {
    list.add(x); // x is a reference to Callable<V>
}

      

Similar to the following line in C ++:

const std::vector<T> list(N, x); // x is an instance of T

      

+3


source to share


2 answers


Like this:



int N = 8;
Callable<Void> a = null;
List<Callable<Void>> nCopies = Collections.nCopies(N, a);

      

+7


source


Returns an immutable list from the documentation . If it's good, this is the best choice.nCopies()

Alternatively you can use Arrays.fill()

to populate an array with the same value, which you can convert toList



Arrays.fill(callableArray, x);
List<Callable<V>> list = new ArrayList(Arrays.asList(array));

      

+1


source







All Articles