0

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!

Christian
  • 576
  • 1
  • 4
  • 16
  • If youre looking for an very efficient solution (as it seems because you're saying copying the array is not acceptable): You can implement your own `List`, given any `Object` and `size` which simply returns the Object for all calls to `get(int)` with `0 <= index < size`. – Felix Nov 02 '21 at 15:11
  • Of course, this would be fast. But I strongly need an ArrayList as result. Thank you for your hint. – Christian Nov 02 '21 at 15:27
  • I didnt know before, but this is actually exactly what `Collections.nCopies` does. Learned a new thing today :) – Felix Nov 02 '21 at 15:28

1 Answers1

7

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243