Does Lombok toBuilder() method creates deep copy of fields

Yes, the @Builder(toBuilder=true) annotation doesn't perform a deep copy of the object and only copies the reference of the field.

List<Book> books = new ArrayList<>();
Library one = new Library(books);
Library two = one.toBuilder().build();
System.out.println(one.getBooks() == two.getBooks()); // true, same reference

You can make a copy of the collection manually with one simple trick:

    List<Book> books = new ArrayList<>();
    Library one = new Library(books);
    Library two = one.toBuilder()
        .books(new ArrayList<>(one.getBooks))
        .build();
    System.out.println(one.getBooks() == two.getBooks()); // false, different refs

Tags:

Java

Lombok