如何将ArrayList传递给varargs方法参数? [英] How to pass an ArrayList to a varargs method parameter?

查看:168
本文介绍了如何将ArrayList传递给varargs方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically I have an ArrayList of locations:

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

在此我调用以下方法:

.getMap();

getMap()方法中的参数是:

the parameters in the getMap() method are:

getMap(WorldLocation... locations)

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

The problem I'm having is I'm not sure how to pass in the WHOLE list of locations into that method.

我试过

.getMap(locations.toArray())

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

but getMap doesn't accept that because it doesn't accept Objects[].

现在,如果我使用

.getMap(locations.get(0));

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

it will work perfectly... but I need to somehow pass in ALL of the locations... I could of course make keep adding locations.get(1), locations.get(2) etc. but the size of the array varies. I'm just not use to the whole concept of an ArrayList

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

What would be the easiest way to go about this? I feel like I'm just not thinking straight right now.

推荐答案

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

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

toArray(new WorldLocation [0])也可以,但你会无缘无故地分配零长度数组。)

(toArray(new WorldLocation[0]) also works, but you would allocate a zero length array for no reason.)

这是一个完整的例子:

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()]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...






此帖子已被重写为文章这里

这篇关于如何将ArrayList传递给varargs方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆