我有以下Book
類(我省略了不相關的代碼)。在構造函數中檢查列表時的正確做法
public final class Book {
public Book(String bookTitle, List<Author> listofAuthors, int numberofchapters, String ISBN)
{
//Ommitted other variable initializations.
this.checkAuthors(listofAuthors);
this.listofAuthors = Collections.unmodifiableList(new ArrayList<Author>(listofAuthors));
}
private void checkAuthors(List<Author> checkifEmpty)
{
if(checkifEmpty == null){
throw new IllegalArgumentException("List of authors is null");
}
if (checkifEmpty.size() == 0){
throw new IllegalArgumentException("The authors list contains no authors");
}
for (Author checkEmpty : checkifEmpty){
if(checkEmpty == null){
throw new IllegalArgumentException("A book must have at least one author");
}
}
}
我包括私有方法來檢查作者的List
,以確保該List
集合不爲0,並防止
Author bookAuthor = null;
List<Author> listofAuthors = new ArrayList<Author>();
listofAuthors.add(bookAuthor);
或
List<Author> listofAuthors = null;
Book tlac = new Book("book title goes here", listofAuthors, 30, "isbn goes here");
的發生。
問題:
呼喚從
constructor
一個private
方法和做的工作還有認爲是不好的做法?如果是這樣,我應該如何糾正它?在
private
方法checkAuthors
我使用==
instead ofequals()
。我的目的是檢查存儲在List<Author>
中的對象的值是否爲null
。是這種情況下,我找到了使用==
的作品,如果我使用equals()
它給我null
作爲錯誤信息。在這種情況下正確使用==
,如果不是,我該怎麼做?