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 ?
Advertisement
Answer
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