Java 枚举作为构造函数传递

标签 java lambda enums

我正在尝试从构造函数传递枚举类型的引用以测试一些 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)

最佳答案

替换

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;
}

然后你的程序就可以工作了。

关于Java 枚举作为构造函数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39982680/

相关文章:

java - "NULL not allowed"有两个 @OneToMany 到同一个表

C++ lambda 返回自身

Java8 将对象列表转换为对象的一个​​属性列表

类中的 C# 公共(public)枚举

swift - 通过枚举显示多个 UICollectionViewCells?

java - 如何在自定义 OrderedLinkedList 类中显示从列表中删除了哪些元素?

Java + Maven - 来自测试类的可执行 jar

java - 如何降低环复杂度?

android - 如何将 Lambda 转换为简单的 Java 函数表达式

c# - 在 Azure 搜索文档中使用枚举