javastringarraylist

Add multiple numbered objects to ArrayList


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

String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";

I want to add these String variables to ArrayList, what I am doing now is

ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);        

I am curious, is there a way to use a loop? For example.

for(int i =  1; i <= 100; i++){
     list.add(str+i)//something like this?
}

Solution

  • 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. Also the Collections class (note the s at the end) has static methods that work for all Collection classes and do not require calling Arrays.asList(). For example:

    Collections.addAll( list, strs );
    Collections.addAll( list, "Larry", "Moe", "Curly" );
    

    If you just want a list with only the array elements, you can do it on one line:

      List<String> list = Arrays.asList( strs );
    

    Edit: Many other classes in the Java API support this addAll() method. It's part of the Collection interface. Other classes like Stack, List, Deque, Queue, Set, and so forth implement Collection and therefore the addAll() method. (Yes some of those are interfaces but they still implement Collection.)