Sobes.tech
Junior — Middle

How can you create an immutable copy of a collection using the clone method?

sobes.tech AI

Answer from AI

In Java, the clone() method is used to create a shallow copy of an object. To make a collection immutable after cloning, you can follow these steps:

  1. Create a copy of the collection using clone() (if the collection supports this method).
  2. Wrap the obtained copy in an unmodifiable wrapper using methods from Collections.

Example for a list:

import java.util.*;

ArrayList<String> original = new ArrayList<>();
original.add("A");
original.add("B");

// Clone
ArrayList<String> cloned = (ArrayList<String>) original.clone();

// Make it unmodifiable
List<String> unmodifiableList = Collections.unmodifiableList(cloned);

// Now unmodifiableList cannot be changed
// unmodifiableList.add("C"); // will throw UnsupportedOperationException

Thus, clone() creates a copy, and Collections.unmodifiableXXX() makes it immutable.