Passing array elements to varargs

安稳与你 提交于 2020-08-22 07:00:40

问题


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.


回答1:


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



回答2:


Yes, you could use Arrays.copyOf(T[], int) like

super.method(Arrays.copyOf(examples, 11));


来源:https://stackoverflow.com/questions/36440996/passing-array-elements-to-varargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!