问题

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

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

我在下面调用以下方法:

.getMap();

getMap()方法中的参数是:

getMap(WorldLocation... locations)

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

我试过了

.getMap(locations.toArray())

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

现在,如果我使用

.getMap(locations.get(0));

它会完美地运作......但是我需要以某种方式传递所有位置...我当然可以继续添加2161502654etc。但阵列的大小各不相同。我只是不习惯anArrayList的整个概念

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


#1 热门回答(227 赞)

使用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


#2 热门回答(7 赞)

在Java 8中:

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

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

#3 热门回答(3 赞)

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

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

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

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

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

原文链接