【问题标题】:How to add File [] Array content into ArrayList? [duplicate]如何将 File [] 数组内容添加到 ArrayList 中? [复制]
【发布时间】:2013-05-02 12:23:42
【问题描述】:

我有一个数组:

File [] temp=null;

我有一个 arrayListFile 类型:

List <File> tempList = new ArrayList <File>();

现在我想将temp 的内容添加到tempList。所以任何人都可以请告诉我我该怎么做?

【问题讨论】:

  • 循环遍历temp数组并将每个文件添加到tempList
  • 其他人都知道,使用 for 循环将数组内容添加到 ArrayList 会在 Android Studio 中向您发出警告,提示您使用 ArrayListaddAll() 方法。你仍然可以这样做,但由于某种原因 Android Studio 不喜欢它(也许使用该方法更有效?)

标签: java arrays arraylist


【解决方案1】:

试试这个

tempList.addAll(Arrays.asList(temp));

【讨论】:

【解决方案2】:

如果你不打算更新数组的内容(添加/删除元素),它可以很简单

List<File> tempList = Arrays.asList(temp);

当然,如果您想要一个可以进一步操作的列表,您仍然可以执行类似的操作

List<File> tempList = new ArrayList<File>(Arrays.asList(temp));

【讨论】:

  • 第二行代码应该是List&lt;File&gt; tempList = new ArrayList&lt;&gt;(Arrays.asList(temp));,注意ArrayList&lt;&gt;中的菱形
  • 不知道为什么我错过了这个大声笑。让我解决这个问题
【解决方案3】:

使用关注

List<File>tempList = Arrays.asList(temp);

【讨论】:

    【解决方案4】:

    您可以遍历数组并将每个元素添加到列表中。

    for (File each : temp)
      tempList.add(each);
    

    【讨论】:

      【解决方案5】:

      您可以为此使用集合库调用:

      Arrays.asList(temp);
      

      【讨论】:

        猜你喜欢
        • 2011-06-07
        • 2018-10-05
        • 1970-01-01
        • 1970-01-01
        • 2014-03-17
        • 1970-01-01
        • 2012-02-15
        相关资源
        最近更新 更多