【问题标题】:How to add elements of a string array to a string array list?如何将字符串数组的元素添加到字符串数组列表中?
【发布时间】:2012-10-02 22:42:22
【问题描述】:

我正在尝试将字符串数组作为参数传递给 Wetland 类的构造函数; 我不明白如何将字符串数组的元素添加到字符串数组列表中。

import java.util.ArrayList;

public class Wetland {
    private String name;
    private ArrayList<String> species;
    public Wetland(String name, String[] speciesArr) {
        this.name = name;
        for (int i = 0; i < speciesArr.length; i++) {
            species.add(speciesArr[i]);
        }
    }
}

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    Arrays.asList() 方法只返回List 类型

    char [] arr = { 'c','a','t'};    
    ArrayList<Character> chars = new ArrayList<Character>();
    

    要将数组添加到列表中,首先将其转换为列表,然后调用addAll

    List arrList = Arrays.asList(arr);
    chars.addAll(arrList);
    

    下面这行会导致编译错误

    chars.addAll(Arrays.asList(arr));
    

    【讨论】:

      【解决方案2】:
      public class duplicateArrayList {
      
      
          ArrayList al = new ArrayList();
          public duplicateArrayList(Object[] obj) {
      
              for (int i = 0; i < obj.length; i++) {
      
                  al.add(obj[i]);
              }
      
              Iterator iter = al.iterator();
              while(iter.hasNext()){
      
                  System.out.print(" "+iter.next());
              }
          }
      
          public static void main(String[] args) {
      
      
          String[] str = {"A","B","C","D"};
      
          duplicateArrayList dd = new duplicateArrayList(str);
      
          }
      
      }
      

      【讨论】:

        【解决方案3】:

        在 Java 8 中,此语法大大简化,可用于简洁地完成此转换。

        请注意,您需要将您的字段从具体实现更改为List 接口才能顺利工作。

        public class Wetland {
            private String name;
            private List<String> species;
            public Wetland(String name, String[] speciesArr) {
                this.name = name;
                species = Arrays.stream(speciesArr)
                                .collect(Collectors.toList());
            }
        }
        

        【讨论】:

          【解决方案4】:

          我想我会把这个添加到组合中:

          Collections.addAll(result, preprocessor.preprocess(lines));
          

          这是 Intelli 建议的更改。

          来自 javadocs:

          Adds all of the specified elements to the specified collection.
          Elements to be added may be specified individually or as an array.
          The behavior of this convenience method is identical to that of
          <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely
          to run significantly faster under most implementations.
           
          When elements are specified individually, this method provides a
          convenient way to add a few elements to an existing collection:
          <pre>
          Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
          </pre>

          【讨论】:

            【解决方案5】:
            ArrayList<String> arraylist= new ArrayList<String>();
            
            arraylist.addAll( Arrays.asList("mp3 radio", "presvlake", "dizalica", "sijelice", "brisaci farova", "neonke", "ratkape", "kuka", "trokut")); 
            

            【讨论】:

              【解决方案6】:

              你已经有内置的方法:-

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

              注意:- 你应该使用List&lt;String&gt; species 而不是ArrayList&lt;String&gt; species

              Arrays.asList 返回一个不同的ArrayList -> java.util.Arrays.ArrayList 不能转换为java.util.ArrayList

              那么你将不得不使用addAll 方法,这不太好。所以就用List&lt;String&gt;

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

                  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]
              

              【讨论】:

              • @rorrohprog.. 它不返回 Object,而是返回 List,其中 T 是您传递的数组类型。见docs.oracle.com/javase/7/docs/api/java/util/…
              • @rorrohprog。我认为您应该尝试此代码。并查看我提供链接的文档..
              • @RohitJain 你不能从java.util.Arrays.ArrayList 转换(结果从Arrays.asList()java.util.ArrayList
              • @maba。是的,编辑了帖子。 ArrayList 返回的 asList 方法不同。
              • 需要注意的是Collections.addAll()是首选方法:这个便捷方法的行为与c.addAll(Arrays.asList(elements))的行为相同,但是这个方法在大多数实现下可能运行得更快。(Javadoc)
              【解决方案7】:

              Arrays.asList 是 Array 和集合框架之间的桥梁,它返回一个由 Array 支持的固定大小的 List。

              species = Arrays.asList(speciesArr);
              

              【讨论】:

              • Arrays.asList 返回一个对象!
              • @rorrohprog 如果您阅读文档docs.oracle.com/javase/6/docs/api/java/util/…,它会说它返回List&lt;T&gt;
              • @rorrohprog,为什么不能编译?我有它编译?我可以看到这无法编译的唯一原因是您使用了错误的 ArraysList 类。
              【解决方案8】:

              我更喜欢这个,

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

              原因是 Arrays.asList() 方法将创建一个固定大小的列表。因此,如果您直接将其存储到物种中,那么您将无法再添加任何元素,仍然不是只读的。您当然可以编辑您的项目。所以把它放到临时列表中。

              替代方案是,

              Collections.addAll(species, speciesArr);
              

              在这种情况下,您可以添加、编辑、删除您的项目。

              【讨论】:

                【解决方案9】:

                Arrays.asList 是 Java 中用于将数组变量转换为 List 或 Collection 的便捷函数。为了更好地理解,请考虑以下示例:

                package com.stackoverflow.works;
                
                import java.util.ArrayList;
                import java.util.Arrays;
                import java.util.List;
                
                public class Wetland {
                    private String name;
                    private List<String> species = new ArrayList<String>();
                
                    public Wetland(String name, String[] speciesArr) {
                        this.name = name;
                        this.species = Arrays.asList(speciesArr);
                    }
                
                    public void display() {
                        System.out.println("Name: " + name);
                        System.out.println("Elements in the List");
                        System.out.println("********************");
                        for (String string : species) {
                            System.out.println(string);
                        }
                    }
                
                    /*
                     * @Description: Method to test your code
                     */
                    public static void main(String[] args) {
                        String name = "Colors";
                        String speciesArr[] = new String [] {"red", "blue", "green"};
                        Wetland wetland = new Wetland(name, speciesArr);
                        wetland.display();
                    }
                
                }
                

                输出:

                【讨论】:

                  【解决方案10】:

                  您应该在尝试添加项目之前实例化您的 ArrayList

                  private List<String> species = new ArrayList<String>();
                  

                  【讨论】:

                  • 这不是问题真正要问的。
                  【解决方案11】:

                  使用asList() 方法。来自java文档asList

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

                  【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2020-03-08
                  相关资源
                  最近更新 更多