【问题标题】:How can I pass the Strings from an ArrayList<String> to a method that takes in multiple Strings?如何将字符串从 ArrayList<String> 传递给接受多个字符串的方法?
【发布时间】:2013-08-30 19:12:47
【问题描述】:

我有一个带有字符串的 ArrayList 和一个可以接受任意数量的字符串作为参数的方法。

ArrayList<String> list = new ArrayList<String>();
// Filling the list with strings...

public addStrings(String... args) {
    // Do something with those Strings
}

现在我想将这些字符串从我的数组列表传递给该方法。我怎样才能做到这一点?我如何称呼addStrings() 请注意,arraylist 中的字符串数量可能会有所不同。

【问题讨论】:

    标签: android string arraylist variadic-functions


    【解决方案1】:

    你可以这样做:

    ArrayList<String> list = new ArrayList<String>();
    // Filling the list with strings...
    
        String[] stringArray = new String[list.size()];
        list.toArray(stringArray);
        addStrings(stringArray);
    
    public addStrings(String... args) {
        // Do something with those Strings
    }
    

    在原始数组中传递您的字符串。来自varargs 文档:

    最后一个参数类型后面的三个句点表示最后一个参数可以作为数组或参数序列传递。

    您需要做的就是从您的List 派生一个String[],然后将其传递给addStrings(String... args) 方法。

    感谢this 问题的文档链接。

    【讨论】:

    • 好的,但是如果只在运行时知道参数的数量,我应该如何实现这部分String s = String.format("%s, %s, %s", strings);
    • 这只是我所说的使用的一个例子。我会根据你的情况调整我的例子。
    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2015-05-27
    • 2011-06-29
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多