我试图从构造函数传递枚举类型的引用来测试一些lambda,方法引用和Stream
。当我尝试实例化类时,我在枚举上遇到错误。
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)
答案 0 :(得分:2)
替换
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;
}
你的程序会运作。
答案 1 :(得分:1)
正如@djointster所说,COMPUTING
应为Topic.COMPUTING
。
但是,由于private List<String> authors
与构造函数中的ArrayList<String> author
不同,您的代码仍无效。
所以你应该改变这个:
ArrayList<String> authors;
//to
List<String> authors;
在构造函数中。