How to clear a particular list in java

I want to clear this list named tempList on line 25 but whenever i do tempList.clear() or tempList.removeAll() it clears even the other List i.e holderList. The thing is i want to set the tempList to empty. how to do it without effecting other List.

First, please try to use code blocks when pasting code snippets. Like this:

Some Java code here

Second, your problem is that you are reassigning the holderList variable to point at the tempList variable so they are pointing to the same list. The original list that holderList was assigned to before it was reassigned (which numbers is also pointing at) is no longer accessible by using the holderList variable. You can still access that list by using the numbers variable in your current code.

To avoid an X-Y problem, why do you need to clear the tempList at all? The variable is only in scope during the method and once it goes out of scope it will be garbage collected.

thank you so much @jmrunkle

1 Like