I was reading this page about using the new
keyword in the constructor, and I was wondering if it applies to copy constructors for collections.
Suppose I have a Book
class and a collection to store a set
of authors
.
class Book {
private String title;
private Set<Author> authorsSet;
Book (title, authors){
this.title = title
this.authorsSet = Collections.unmodifiableSet(new HashSet<Author>(authors))
}
}
It's a good idea to make a defensive copy so that client code cannot change the internals of authorsSet
.
Is calling this.authorsSet = Collections.unmodifiableSet(new HashSet<Author>(authors))
a violation of the guideline that a constructor shouldn't call the new
keyword? If so, how do we make a defensive copy without the new
keyword?
set
to another. The constructor is actually doing work with theset
.