Sobes.tech
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:

  1. 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);
  1. clone() method — some collections implement the Cloneable interface and have a clone() method that creates a shallow copy:
ArrayList<String> copy = (ArrayList<String>) original.clone();
  1. 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.

How can a duplicate of a collection be made in… - sobes.tech