How to pass elements of an arrayList to variadic function

前端 未结 3 1604
长情又很酷
长情又很酷 2020-12-11 00:23

I\'ve got an arrayList filled with elements. I would like to pass the elements of that array list as arguments to a variadic function.

My function

p         


        
相关标签:
3条回答
  • 2020-12-11 00:50

    The construct IEntityModifier... is syntactic sugar for IEntityModifier[]

    See the appropriate JLS section (8.4.1 Formal Parameters)

    0 讨论(0)
  • 2020-12-11 01:02

    Just do:

    new SequenceEntityModifier(arr.toArray(new IEntityModifier[arr.size()]));
    

    This copies the ArrayList to the given array and returns it. All vararg functions can also take arrays for the argument, so for:

    public void doSomething(Object... objs)
    

    All the legal calls are:

    doSomething(); // Empty array
    doSomething(obj1); // One element
    doSomething(obj1, obj2); // Two elements
    doSomething(new Object[] { obj1, obj2 }); // Two elements, but passed as array
    

    One caveat:

    Vararg calls involving primitive arrays don't work as you would expect. For example:

    public static void doSomething(Object... objs) {
        for (Object obj : objs) {
            System.out.println(obj);
        }
    }
    
    public static void main(String[] args) {
        int[] intArray = {1, 2, 3};
        doSomething(intArray);
    }
    

    One might expect this to print 1, 2, and 3, on separate lines. Instead, it prints something like [I@1242719c (the default toString result for an int[]). This is because it's ultimately creating an Object[] with one element, which is our int[], e.g.:

    // Basically what the code above was doing
    Object[] objs = new Object[] { intArray };
    

    Same goes for double[], char[], and other primitive array types. Note that this can be fixed simply by changing the type of intArray to Integer[]. This may not be simple if you're working with an existing array since you cannot cast an int[] directly to an Integer[] (see this question, I'm particularly fond of the ArrayUtils.toObject methods from Apache Commons Lang).

    0 讨论(0)
  • 2020-12-11 01:07

    I always create an overload that takes Iterable< ? extends IEntityModifier >, and make the variadic version forward to this one using Arrays.asList(), which is cheap.

    0 讨论(0)
提交回复
热议问题