Add multiple String variables to ArrayList

前端 未结 6 2124
爱一瞬间的悲伤
爱一瞬间的悲伤 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:42

    If strX would be class fields then you could try using reflection - link to example of accessing fields and methods.

    If it is local variable then you can't get access to its name so you will not be able to do it (unless str would be array, so you could access its values via str[i] but then you probably wouldn't need ArrayList).

    Update:

    After you updated question and showed that you have 100 variables

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

    I must say that you need array. Arrays ware introduced to programming languages precisely to avoid situation you are in now. So instead of declaring 100 separate variables you should use

    String[] str = {"abc", "123", "aaa", ... , "zzz"};
    

    and then access values via str[index] where index is value between 0 and size of your array -1, which in you case would be range 0 - 99.


    If you would still would need to put all array elements to list you could use

    List elements = new ArrayList<>(Arrays.asList(str));
    

    which would first

    Arrays.asList(str)
    

    create list backed up by str array (this means that if you do any changes to array it will be reflected in list, and vice-versa, changes done to list from this method would affect str array).

    To avoid making list dependant on state of array we can create separate list which would copy elements from earlier list to its own array. We can simply do it by using constructor

    new ArrayList<>(Arrays.asList(str));
    

    or we can separate these steps more with

    List elements = new ArrayList<>();//empty list
    elements.addAll(Arrays.asList(str));//copy all elements from one list to another
    

提交回复
热议问题