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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With