【问题标题】:How to pass an ArrayList to a varargs method parameter?如何将 ArrayList 传递给 varargs 方法参数?
【发布时间】:2012-04-09 11:04:52
【问题描述】:

基本上我有一个位置的 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


【解决方案1】:

来源文章:Passing a list as an argument to a vararg method


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

【讨论】:

  • 这项操作在内存和速度方面的成本有多大?
  • 如果涉及更多模板,这将不会在没有警告的情况下工作。例如。 someMethod(someList.toArray(new ArrayList&lt;Something&gt;[someList.size()])) 会给你一个非常烦人的警告,如果函数超过几行(因为你可以为整个函数禁止它,或者你必须在一个额外的步骤中创建数组并禁止在你存储它的变量。
  • 显然最快的方法是给出一个零大小而不是数组的大小。简而言之,这是因为编译时常量允许使用优化的方法。 shipilev.net/blog/2016/arrays-wisdom-ancients
  • @JoshM。 Java需要很多东西。 ;) 我也(来自 C# 背景)想念索引运算符。在 C# 中使用字典比在 Java 中使用 HashMap 更流畅。
  • @PerLundberg -- 完全同意。也是目前使用 Java8 工作的主要 C# 开发人员。也许10/11会更好。 :-P
【解决方案2】:

在 Java 8 中:

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

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

【讨论】:

【解决方案3】:

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

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

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

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

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

【讨论】:

  • 这个答案对我有用,因为我想要一个 Lists 的数组,但无法实例化一个通用数组以使用 Array.toArray。
  • * List.toArray
【解决方案4】:

你可以这样做:

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

或

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

或

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

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

【讨论】:

  • 第二种方案更好!
  • 第三种解决方案给出一个空白数组,不要使用它。
【解决方案5】:

虽然这里标记为已解决,但我的 KOTLIN RESOLUTION

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

bundleOf 有可变参数

【讨论】:

  • 这对 kotlin 来说是一个很好的答案,但它不太可能帮助很多人,因为这个问题被标记为 java
猜你喜欢
  • 1970-01-01
  • 2011-07-18
  • 2016-11-01
  • 2011-06-29
  • 2021-12-13
  • 2012-02-23
  • 2011-07-25
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多