Passing array elements to varargs Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Passing array elements to varargs without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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));
    }
}
We are here to answer your question about Passing array elements to varargs - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji