Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Lombok toBuilder() method creates deep copy of fields

Tags:

java

lombok

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 ?

like image 944
sarup dalwani Avatar asked Jun 28 '19 13:06

sarup dalwani


2 Answers

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
like image 91
Karol Dowbecki Avatar answered Oct 15 '22 20:10

Karol Dowbecki


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
like image 20
Anton Ermakov Avatar answered Oct 15 '22 21:10

Anton Ermakov