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 arraysArray.new(10) { [] }
Ruby, same as PythonIn 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?
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With