Saffie
Saffie

Reputation: 555

After Object.clone, why is element's address in a nested ArrayLIst<String> is different but not for a nested ArrayList<Integer>?

Let's say I have a class Book and one of its attribute is an ArrayList of Strings with the names of the protagonists. When I call clone() on the Book, I expect it to do a shallow copy, i.e., the cloned Book object has its own memory location and attributes like Strings and ints as well but an ArrayList attribute will refer to the same existing ArrayList from the prototype Book. However, when I print this information then it appears that the ArrayList has the same address, but the Strings do not. I find this surprising. Can you explain what happens?

import java.util.List;

public class CloneExample {
    public static void main(String[] args) {
        Story philosophersStoneStory = new Story("Lorem ipsum dolor sit amet consectetuer adipiscing");
        List<String> protagonists = List.of("Harry", "Hermoine", "Ron");
        Book harryPotter = new Book("Harry Potter", 25, philosophersStoneStory, protagonists);

        Book harryPotterRipOff = null;
        Object book = null;
        try {
            //WATCH OUT: STUPID DANGEROUS CAST HERE!!!
            harryPotterRipOff = (Book) harryPotter.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        println("The original");
        printBookDetails(harryPotter);

        println("");

        println("The rip-off clone");
        printBookDetails(harryPotterRipOff);

        println("");
        println("The book is new, but the story is actually the same..");
    }

    public static void println(Object obj) {
        System.out.println(obj);
    }

    public static void printBookDetails(Book book) {
        println(book);
        println(book.getAuthor());
        println(System.identityHashCode(book.getProtagonists()));
        println("Harry lives at: " + System.identityHashCode(book.getProtagonists().get(0).hashCode()));
    }
}

Output is:

The original
Book@65ae6ba4
Story@48cf768c
ArrayList is located at: 1509514333
Harry lives at: 184966243

The rip-off clone
Book@768debd
Story@48cf768c
ArrayList is located at: 1509514333
Harry lives at: 1225616405

The ArrayList is at the same address, but the String "Harry" is not.

Upvotes: 0

Views: 71

Answers (0)

Related Questions