Create java collection with n clones of an object

后端 未结 4 1489
借酒劲吻你
借酒劲吻你 2020-12-11 05:30

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:

4条回答
  •  有刺的猬
    2020-12-11 05:49

    • vector > = new vector >(10); Is not syntactically correct but lets say you meant vector > foo(10);. 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:

    • What other construct (besides a loop did you have in mind)? I believe there will be a loop at some level.
    • How do you really want to be initializing the ArrayList objects inside the outer ArrayList? For example what size do you want them to be? Should they be initially populated with anything? How big do you expect them to grow? Do they need to be uniform size or does it makes sense for some to be bigger/smaller? Does it make sense to lazily initialize these lists?

    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);
    

提交回复
热议问题