如何将ArrayList传递给varargs方法参数?

问题描述 投票:176回答:4

基本上我有一个位置的ArrayList:

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的整个概念

最简单的方法是什么?我觉得我现在不想直接思考。

java variadic-functions
4个回答
269
投票

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

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

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("wordld");

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

这篇文章已被重写为文章here


24
投票

在Java 8中:

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

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

7
投票

使用Guava接受的答案的较短版本:

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

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

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

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

0
投票

你可以这样做:getMap(locations.toArray(new WorldLocation[locations.size()]));getMap(locations.toArray(new WorldLocation[0]));getMap(new WorldLocation[locations.size()]);

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

© www.soinside.com 2019 - 2024. All rights reserved.