簡體   English   中英

如何將 ArrayList 傳遞給可變參數方法參數?

[英]How to pass an ArrayList to a varargs method parameter?

基本上我有一個位置的 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的整個概念

解決這個問題的最簡單方法是什么? 我覺得我現在只是沒有直接思考。

源文章: 將列表作為參數傳遞給 vararg 方法


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

在 Java 8 中:

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

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

使用番石榴的接受答案的較短版本:

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

可以通過靜態導入 toArray 進一步縮短:

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

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

你可以做:

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

或者

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

或者

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

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

雖然在這里標記為已解決,但我的KOTLIN RESOLUTION

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

bundleOf 具有可變參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM