That will not work since you are stating that str = "str" + k
, which means that str
will have values of str1
, str2
, etc. These values represent string literals, and not variable names. To go round your problem you can do this:
List<String> fruit = new ArrayList<String>();
fruit.add((String) optionlist1.get(i));
fruit.add((String) optionlist2.get(i));
fruit.add((String) optionlist3.get(i));
for(String str : fruit)
{
System.out.println(str);
}
What you are trying to achieve is possible through the Reflection API
(more on that here), however I think that for your particular problem, using reflection might be a little bit overkill, so it might be better to stick with the easier solutions.
EDIT: This code should do what you are after through the use of reflection:
public static List<String> lst0 = new ArrayList<String>();
public static List<String> lst1 = new ArrayList<String>();
public static void main(String[] args) throws NoSuchElementException, NoSuchFieldException, IllegalAccessException
{
lst0.add("abc");
lst1.add("def");
Class thisClass = SOTest.class;
for(int i = 0; i < 2; i++)
{
Field field = thisClass.getField("lst" + i);
List<String> lst = (List<String>) field.get(new ArrayList<String>());
System.out.println(lst.get(0));
}
}