Lombok toBuilder() 方法是否创建了字段的深层副本

2022-09-03 12:50:23

我正在使用对象实例来创建构建器实例,然后使用构建方法来创建新实例。原始对象有一个列表,新对象是引用了同一列表还是它的副本?toBuilder()

@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();

lib2 书籍会引用与 lib1 书籍相同的列表吗?


答案 1

是的,批注不会执行对象的深层复制,而只会复制字段的引用。@Builder(toBuilder=true)

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

答案 2

您可以使用一个简单的技巧手动制作集合的副本:

    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

推荐