问题
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