Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create java collection with n clones of an object

In Java, is there a one-line way to create a collection that is initialized with n clones of an object?

I'd like the equivalent of this:

  • foo = vector<vector<int> >(10); c++, creates 10 different empty vectors
  • [ [] for i in range(10) ] Python, an array of 10 distinct empty arrays
  • Array.new(10) { [] } Ruby, same as Python

In Java, I've only found

new ArrayList<ArrayList<Integer> >(Collections.nCopies(10, new ArrayList<Integer>()))

However, this is not equivalent to the other examples, because the lists alias.

Is there a way to create an array of distinct object clones, without using a for loop, and preferably without resorting to external libraries?

like image 839
Sjlver Avatar asked Nov 10 '14 22:11

Sjlver


People also ask

What is clone of collections in Java?

The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.


1 Answers

If you're using Java 8 you could use its streams:

Stream.generate(ArrayList<Integer>::new)
    .limit(10).collect(Collectors.toList());

The Stream.generate() method takes a Supplier that knows how to produce a value and generates an infinite stream of those values (each value is obtained by calling the supplier again, so they are all different, unlike Collections.nCopies()). Placing a limit() on the stream and then collecting the results to a list thus yields a list of distinct entries.

Note that starting in Java 16 Stream has a toList() method, so this can become a little cleaner:

Stream.generate(ArrayList<Integer>::new).limit(10).toList();
like image 89
David Conrad Avatar answered Nov 05 '22 18:11

David Conrad