CLONE A LIST
Cloning a list in Java using the addAll() method involves creating a copy of an existing list. To do this, you start by adding elements to an original list. Then, you use the addAll() method to copy all the elements from the original list to a new list.
The new list becomes a separate copy, and any modifications made to it won’t affect the original list, demonstrating that the two lists are independent. This approach is useful when you need a duplicate of a list but want to keep the original list unchanged.
import java.util.ArrayList; import java.util.List; public class CloneList { public static void main(String[] args) { List<String> firstList = new ArrayList<>(); firstList.add("sun"); firstList.add("moon"); firstList.add("star"); List<String> clonedList = new ArrayList<>(); clonedList.addAll(firstList); System.out.println("first List: " + firstList); System.out.println("Cloned List: " + clonedList); clonedList.set(0, "Z"); System.out.println("Modified Cloned List: " + clonedList); System.out.println("Original List remains unchanged: " + firstList); } }
STEPS TO FOLLOW
- Create an empty list firstList.
- Add elements “sun”, “moon”, and “star” to firstList.
- Create a new empty list clonedList.
- Copy all elements from firstList to clonedList using addAll().
- Print firstList and clonedList to show they are identical.
- Change the first element of clonedList from “sun” to “Z”.
- Print the modified clonedList to show the change.
- Print firstList again to confirm it remains the same.
- Observe that firstList is unaffected by the change to clonedList.
- Demonstrate that clonedList is a separate list with its own changes.
OUTPUT
first List: [sun, moon, star]
Cloned List: [sun, moon, star]
Modified Cloned List: [Z, moon, star]
Original List remains unchanged: [sun, moon, star]