如何传递一个数组列表到一个可变参数方法参数?

基本上我有一个位置的数组列表

ArrayList<WorldLocation> locations = new ArrayList<WorldLocation>();

下面我调用以下方法:

.getMap();

getMap()方法中的参数是:

getMap(WorldLocation... locations)

我遇到的问题是我不确定如何将locations的整个列表传递到该方法。

我试过了

.getMap(locations.toArray())

但是getMap不接受,因为它不接受Objects[]。

现在如果我使用

.getMap(locations.get(0));

它会工作得很好……但我需要以某种方式传递所有的位置…当然,我可以继续添加locations.get(1), locations.get(2)等,但数组的大小是不同的。我只是不习惯ArrayList的整个概念

最简单的方法是什么?我觉得我现在脑子不太清醒。

199595 次浏览

来源:将列表作为参数传递给可变参数方法


使用toArray(T[] arr)方法。

.getMap(locations.toArray(new WorldLocation[0]))

下面是一个完整的例子:

public static void method(String... strs) {
for (String s : strs)
System.out.println(s);
}


...
List<String> strs = new ArrayList<String>();
strs.add("hello");
strs.add("world");
    

method(strs.toArray(new String[0]));
//     ^^^^^^^^^^^^^^^^^^^^^^^^^^^
...

用番石榴做的一个简短的公认答案:

.getMap(Iterables.toArray(locations, WorldLocation.class));

可以通过静态导入toArray进一步缩短:

import static com.google.common.collect.toArray;
// ...


.getMap(toArray(locations, WorldLocation.class));

在Java 8中:

List<WorldLocation> locations = new ArrayList<>();


.getMap(locations.stream().toArray(WorldLocation[]::new));

你可以:

getMap(locations.toArray(new WorldLocation[locations.size()]));

getMap(locations.toArray(new WorldLocation[0]));

getMap(new WorldLocation[locations.size()]);

@SuppressWarnings("unchecked")需要删除ide警告。

虽然它在这里被标记为已解决,但我的芬兰湾的科特林决议

fun log(properties: Map<String, Any>) {
val propertyPairsList = properties.map { Pair(it.key, it.value) }
val bundle = bundleOf(*propertyPairsList.toTypedArray())
}

bundleOf有可变参数