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:
vector
Is not syntactically correct but lets say you meant vector
. You are using the fill constructor which will initialize the container size and then initialize each element to a copy of the value_type
parameter (or the default constructor if you didn't specify anything). This will use a loop.
[ [] for i in range(10) ]
and Array.new(10) { [] }
are just doing the looping on 1 line and copying an empty list type structure in.
As you indicated the nCopies
method is not equivalent because the result is immutable and you are not creating copies (or clones). The reference to the same element is used when every index is accessed. See the openjdk copies implementation for reference.
Some of the difficulties with java is there is no guarantee of a default constructor like in C++ and the syntax is a bit different than most scripting languages. This may be a good opportunity to take a second and understand what is going on under the covers to ensure your solution is not doing more work than necessary. Some follow up questions to ask yourself:
To help answer these questions it may be good practice to write your own generic static initializer for your use case. After you get the simple case down if your use case varies it may make your solution more generic to use the Factory Pattern to initialize your inner lists. As you can see there is a good deal of issues to consider and in the simple case you may just end up with something like:
public static List> newListofLists(int outerSize, int innerSize, T value) {
List> outer = new ArrayList>(outerSize);
for (int i = 0; i < outer.size(); ++i) {
List inner = new ArrayList(innerSize);
outer.add(inner);
for (int j = 0; j < inner.size(); ++j) {
inner.add(value);
}
}
return outer;
}
This can then be used to initialize your lists in one line like:
List> myList = newListofLists(10, 5, -1);