javalombok

Does Lombok toBuilder() method create deep copy of fields?


I am using toBuilder() on an object instance to create a builder instance and then build method to create new instance. The original object has a list, does the new object has reference to same list or a copy of it?

@Getter
@Setter
@AllArgsConstructor
public class Library {

    private List<Book> books;

    @Builder(toBuilder=true)
    public Library(final List<Book> books){
         this.books = books;
    }

}

Library lib2  = lib1.toBuilder().build();

Will lib2 books refer to same list as lib1 books ?


Solution

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