Create java collection with n clones of an object

后端 未结 4 1503
借酒劲吻你
借酒劲吻你 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:52

    Even with the introduction of Java 8 Supplier, there is unfortunately not a succinct one-liner like nCopies. To be honest, I don't know why. (Though @DavidConrad has shown that Stream can do this.)

    You can easily create one yourself, for example:

    public static > L fill(
            L list, Supplier sup, int n) {
        for(; n > 0; --n)
            list.add(sup.get());
        return list;
    }
    

    Call like:

    List> list = ArrayUtils.fill(
        new ArrayList<>, ArrayList::new, 10
    );
    

    For arrays, there is the new method Arrays#setAll:

    Integer[] oneToTen = new Integer[10];
    Arrays.setAll(oneToTen, i -> i + 1);
    List asList = Arrays.asList(oneToTen);
    

    But it is a void method so it can't be used in a single statement. (Personal remark: why can't Java API be fluid?)

    Prior to Java 8 there is not a library method to do this and it is more cumbersome to create one. Since clone is protected, it cannot be invoked generically. Reflection can do it but reflection is pretty cumbersome.

提交回复
热议问题