Junior — Middle
Is it possible to reinitialize an ArrayList programmatically by forcibly replacing its contents?
sobes.tech AI
Answer from AI
Yes, it is possible to programmatically clear and reinitialize the contents of an ArrayList. There are several ways to do this:
- Clear the existing list and add new elements:
ArrayList<String> list = new ArrayList<>();
list.add("First element");
// Clear
list.clear();
// Add new elements
list.add("New element 1");
list.add("New element 2");
- Create a new instance of ArrayList and assign it to the variable:
list = new ArrayList<>();
list.add("New element");
The first method is useful if there are references to the list elsewhere and you want to keep the object, while the second is suitable if you can replace the reference with a new object.