且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串数组的元素添加到字符串数组列表中?

更新时间:2023-11-02 14:14:16

你已经有内置的方法:-

You already have built-in method for that: -

List<String> species = Arrays.asList(speciesArr);

注意: - 您应该使用 List;物种 不是 ArrayList物种.

NOTE: - You should use List<String> species not ArrayList<String> species.

Arrays.asList 返回一个不同的 ArrayList -> java.util.Arrays.ArrayList,它不能被类型转换为 java.util.ArrayList.

Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.

那么你就不得不使用 addAll 方法,这不太好.所以只需使用 List

Then you would have to use addAll method, which is not so good. So just use List<String>

注意: - Arrays.asList 返回的列表是一个固定大小的列表.如果您想向列表中添加某些内容,则需要创建另一个列表,并使用 addAll 向其中添加元素.所以,那么你***采用下面的第二种方式:-

NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -

    String[] arr = new String[1];
    arr[0] = "rohit";
    List<String> newList = Arrays.asList(arr);

    // Will throw `UnsupportedOperationException
    // newList.add("jain"); // Can't do this.

    ArrayList<String> updatableList = new ArrayList<String>();

    updatableList.addAll(newList); 

    updatableList.add("jain"); // OK this is fine. 

    System.out.println(newList);       // Prints [rohit]
    System.out.println(updatableList); //Prints [rohit, jain]