Junior — Middle
How can a duplicate of a collection be made in memory?
sobes.tech AI
Answer from AI
To create a duplicate of a collection in memory in Java, you can use several approaches:
- Copy constructor — many collections have a constructor that accepts another collection, creating a shallow copy:
List<String> original = new ArrayList<>();
original.add("A");
original.add("B");
List<String> copy = new ArrayList<>(original);
clone()method — some collections implement theCloneableinterface and have aclone()method that creates a shallow copy:
ArrayList<String> copy = (ArrayList<String>) original.clone();
- Using streams — you can create a new collection by copying the elements:
List<String> copy = original.stream().collect(Collectors.toList());
Important: all these methods create a shallow copy — objects inside the collection are not cloned but their references are copied. For a deep copy, each element must be cloned individually.