如何将arrayList的元素传递给可变参数函数 [英] How to pass elements of an arrayList to variadic function
问题描述
我有一个充满元素的 arrayList.我想将该数组列表的元素作为参数传递给可变参数函数.
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.
我的功能
public SequenceEntityModifier(final IEntityModifier... pEntityModifiers)
我的数组列表
ArrayList<IEntityModifier> arr = new ArrayList<IEntityModifier>();
arr.add(new MoveXModifier(1, 50, 120));
arr.add(new MoveXModifier(1, 120, 50));
我想将它传递给函数,就像我会单独传递它们一样.
I'd like to pass it to the function as if I would pass them individually.
new SequenceEntityModifier( /* elements of arr here */ );
这样的事情可能吗?
提前致谢.
推荐答案
只需:
new SequenceEntityModifier(arr.toArray(new IEntityModifier[arr.size()]));
这会将 ArrayList
复制到给定的数组并返回它.所有可变参数函数也可以为参数采用数组,因此:
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)
所有合法的电话是:
doSomething(); // Empty array
doSomething(obj1); // One element
doSomething(obj1, obj2); // Two elements
doSomething(new Object[] { obj1, obj2 }); // Two elements, but passed as array
一个警告:
涉及原始数组的 Vararg 调用不能像您期望的那样工作.例如:
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);
}
人们可能希望这会在单独的行上打印 1
、2
和 3
.相反,它会打印类似 [I@1242719c
(int[]
的默认 toString
结果)之类的内容.这是因为它最终会创建一个带有一个元素的 Object[]
,即我们的 int[]
,例如:
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 };
同样适用于 double[]
、char[]
和其他原始数组类型.请注意,这可以通过将 intArray
的类型更改为 Integer[]
来解决.如果您使用现有数组,这可能并不简单,因为您无法将 int[]
直接转换为 Integer[]
(请参阅 这个问题,我特别喜欢ArrayUtils.toObject
来自 Apache Commons Lang).
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).
这篇关于如何将arrayList的元素传递给可变参数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!