4

I have declared 10 ArrayLists with names arraylist1, arraylist2 and so on.

I want to dynamically change variable name in a for loop:

for (int i = 1; i < 5; i++)
{
   arraylist + (i).clear();
   //arraylist1.clear();
   //arraylist2.clear();
   //arraylist3.clear();
   //arraylist4.clear();
   //arraylist5.clear();

}

Is it possible? If so what is format to do so?

3
  • No, you are not able to change variable name in java (at least not in conventional way). Is it any reason why you want to do this? Commented Jun 16, 2015 at 10:09
  • @user902383: I have created new arraylist's and method and I want to call only the method once in a loop and clear arraylist then add values for that arraylist. Commented Jun 16, 2015 at 10:12
  • 2
    If you have several lists, and you want to clean then in list, why not put them into list, or other collection Commented Jun 16, 2015 at 10:15

3 Answers 3

8

You can not address a variable with its name as string (except with reflection, but that's an overkill for this task).

You can add all these ArrayList's to another List. This is more flexible and, thus, a better option.

List<List<ContactDetails>> lists2 = new ArrayList<List<String>>();
for (int i = 0; i < 10; i++) {
    lists2.add(new ArrayList<ContactDetails>());
}

Or add them to an array and access them by array indexes:

@SuppressWarnings("unchecked")
List<ContactDetails>[] lists = new List[10];
for (int i = 0; i < lists.length; i ++) {
    lists[i] = new ArrayList<ContactDetails>();
}

Now:

for (int i = 1; i < 5; i++)
{
   lists[i].clear();
   lists2.get(i).clear();
}

As both List and array are Iterable, you can use the foreach syntax:

for (List list : lists)
{
   list.clear();
}

for (List list : lists2) {
    list.clear();
}

If you know how to achieve the same with Lambdas / Stream API, please add to the answer.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for quick reply..What if I have arraylist of something like this: ArrayList<ContactDetails> arraylist1;
Thanks for the quick fix. I am getting warning "Type safety: The expression of type List[] needs unchecked conversion to conform to List<ContactDetails>[]" - Do I need to worry about it?
@NickVolynkin: I'm sorry, I was typing too fast without having made a test. I think the best way (without any warning nedded to be supressed) is the variant with the list of lists (lists2)
@xmoex I agree about a list of lists, it's the most flexible option. The new List<ContactDetails>[10] was in my first version, so I made the same mistake.
1

If the ArrayLists are class properties, you can achieve this with reflection:

((ArrayList) getClass().getField("arraylist" + i).get(this)).clear();

3 Comments

What's the exception?
@Stewart why would you think it was?
@Armand sorry, I misread your comment =) Thought it was OP asking about the exception.
1

You can also do this with reflection. But I do not recommend it.

public class SoTest {

    @Test
    public void testWithReflection() throws Exception {
        final MyClass myClass = new MyClass();
        for (int i = 0; i < 10; i++) {
            final Field field = myClass.getClass().getDeclaredField("list" + i);
            field.setAccessible(true);
            final List<String> value = (List<String>) field.get(myClass);
            value.clear();
        }
    }

    class MyClass {
        private List<String> list0 = new ArrayList<>();
        private List<String> list1 = new ArrayList<>();
        private List<String> list2 = new ArrayList<>();
        private List<String> list3 = new ArrayList<>();
        private List<String> list4 = new ArrayList<>();
        private List<String> list5 = new ArrayList<>();
        private List<String> list6 = new ArrayList<>();
        private List<String> list7 = new ArrayList<>();
        private List<String> list8 = new ArrayList<>();
        private List<String> list9 = new ArrayList<>();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.