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<String> 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<String> elements = new ArrayList<>();//empty list
elements.addAll(Arrays.asList(str));//copy all elements from one list to another