[英]Java enum pass as an constructor
我試圖從構造函數傳遞枚舉類型的引用來測試一些lambdas,方法引用和Stream
s。 當我嘗試實例化類時,我在枚舉上遇到錯誤。
public class Book {
private String title;
private List<String> authors;
private int pageCount[];
private Year year;
private double height;
private Topic topic;
public Book (String title, ArrayList<String> author, int pageCount [], Year year, double height, Topic topic )
{
this.title = title;
this.authors = author;
this.pageCount = pageCount;
this.topic = topic;
this.year = year;
this.height = height;
}
public enum Topic
{
MEDICINE, COMPUTING, FICTION, HISTORY
}
public String getTitle(){
return title;
}
public List<String> getAhuthors(){
return authors;
}
public int [] getPageCounts(){
return pageCount;
}
public Topic getTopic()
{
return topic;
}
public Year getPubDate(){
return year;
}
public double getHeight()
{
return height;
}
public static void main(String args [] )
{
Book nails = new Book("Fundamentals of Chinese Fingernail image", Arrays.asList("Li", "Fun", "Li"),
new int [] {256}, Year.of(2014), 25.2, COMPUTING);
Topic test = Topic.COMPUTING;
System.out.println(test);
}
}
這就是我得到的:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
COMPUTING cannot be resolved to a variable at Book.main(Book.java:70)
更換
Book nails = new Book("Fundamentals of Chinese Fingernail image", Arrays.asList("Li", "Fun", "Li"),
new int [] {256}, Year.of(2014), 25.2, COMPUTING);
通過
Book nails = new Book("Fundamentals of Chinese Fingernail image", Arrays.asList("Li", "Fun", "Li"),
new int [] {256}, Year.of(2014), 25.2, Topic.COMPUTING);
編輯:
就像@Voltboyy指出的那樣,你必須改變我之前指出的qhat並將構造函數中的ArrayList<String>
替換為List<String>
如下所示:
public Book(String title, List<String> list, int pageCount[], Year year, double height, Topic topic) {
this.title = title;
this.authors = list;
this.pageCount = pageCount;
this.topic = topic;
this.year = year;
this.height = height;
}
你的程序會起作用。
正如@djointster所說, COMPUTING
應該是Topic.COMPUTING
。
但是,之后您的代碼仍無效,因為private List<String> authors
與構造函數中的ArrayList<String> author
private List<String> authors
不同。
所以你應該改變這個:
ArrayList<String> authors;
//to
List<String> authors;
在構造函數中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.