Passing array elements to varargs

I have the following method on a superclass:

public void method(Example... examples) {
        for (Example e : examples) {
            e.doSomething();
        }
    }

And this is the call on the subclass:

super.method(examples[0], examples[1], examples[2], examples[3], examples[4], examples[5], examples[6], examples[7], examples[8], examples[9], examples[10]);

Is there an easier way to pass the elements? Something like super.method(examples[0 -> 10]) ?

I can’t pass the entire array (super.method(examples)) to the method.

Thank you.

Answer

You can leverage Arrays.copyOfRange(T[], int from, int to) method

super.method(Arrays.copyOfRange(examples, 1, 11)); 

An example is below.

package com.foo;

import java.util.Arrays;

public class TestVarArgs {

    public void test(String...strings){

    }
    public static void main(String[] args) {
        new TestVarArgs().test(Arrays.copyOfRange(args, 1, 11));
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *