Issue
Is there a way to fast initialize a new ArrayList object with X same objects?
Here is an example code:
private List<String> initStringArrayList(int size, String s) {
List<String> list = new ArrayList<>(size);
while (size-- > 0) {
list.add(s);
}
return list;
}
I want to have the same result, but much faster for large "size" values.
Of course, I could use this code:
private List<String> initStringArrayList(int size, String s) {
String[] array = new String[size];
Arrays.fill(array, s);
return new ArrayList<>(Arrays.asList(array));
}
But the constructor of ArrayList<>() would copy the full array instead of using it internal. That would not be acceptable.
Is there another way to do so? I need an ArrayList as result, not just a list. And it should be of any type, not just for strings.
Thank you for any answer!
Solution
Use Collections.nCopies
, and copy it into an ArrayList:
private <T> List<T> initStringArrayList(int size, T s) {
return new ArrayList<>(Collections.nCopies(size, s));
}
This assumes that you really do want a mutable List
at the end. If you can make do with an immutable list with the item size
times, Collections.nCopies(size, s)
by itself would work: it is memory-efficient, fast to allocate etc.
Answered By - Andy Turner