gpt4 book ai didi

Java - 将列表的元素作为参数传递给无限参数方法

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:47:02 25 4
gpt4 key购买 nike

我有一个无限参数的方法:

void X(Object... values){};

以及用户应输入的未知列表。

现在我想将该列表的所有元素传递给方法 X,例如

this.X(list.get(0), list.get(1)......);

谁能告诉我该怎么做?

最佳答案

声明为

的方法
void X(Object... values){};

类似于声明为

的方法
void X(Object[] values){};

并且可以用 Object[] 调用,尽管只有第一个可以用可变数量的参数调用。您可以使用 List.toArray() 将列表转换为数组, 这样你就可以调用 X(list.toArray())。这是演示的示例代码:

import java.util.Arrays;

public class VarargsExample {

public static void foo( Object... args ) {
System.out.println( "foo: "+Arrays.toString( args ));
}

public static void bar( Object[] args ) {
System.out.println( "bar: "+Arrays.toString( args ));
}

public static void main(String[] args) {
// only foo can be called with variable arity arguments
foo( 1, 2, 3 );
// bar( 4, 5, 6 ); // won't compile

// both methods can be called with object arrays
foo( new Object[] { 7, 8, 9 } );
bar( new Object[] { 10, 11, 12 } );

// so both can be called with List#toArray results
foo( Arrays.asList( 13, 14, 15 ).toArray() );
bar( Arrays.asList( 16, 17, 18 ).toArray() );
}
}
foo: [1, 2, 3]
foo: [7, 8, 9]
bar: [10, 11, 12]
foo: [13, 14, 15]
bar: [16, 17, 18]

关于Java - 将列表的元素作为参数传递给无限参数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21862643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com