Add multiple String variables to ArrayList

前端 未结 6 2125
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 18:24

Suppose I have a lot of String Variables(100 for example):

   String str1 = \"abc\";
    String str2 = \"123\";
    String str3 = \"aaa\";
....
    String st         


        
6条回答
  •  春和景丽
    2021-01-14 18:40

    Use an array:

    String[] strs = { "abc","123","zzz" };
    
    for(int i =  0; i < strs.length; i++){
         list.add(strs[i]);  //something like this?
    }
    

    This idea is so popular that there's built-in methods to do it. For example:

      list.addAll( Arrays.asList(strs) );
    

    will add your array elements to an existing list. If you just want a list with only the array elements, you can do it on one line:

      List list = Arrays.asList( strs );
    

提交回复
热议问题