【问题标题】:How to access attributes from an object inside a list? [duplicate]如何从列表中的对象访问属性? [复制]
【发布时间】:2019-04-19 11:02:50
【问题描述】:

嗯,我有一组书籍,我需要用它们来从接口编写方法。但是我不知道如何从这个集合中的对象访问属性或方法。

我试图这样实现,但它说“类型不匹配:无法从元素类型 Object 转换为 Book”。

public class MyCozyLibrary implements SmallLibrary {

private Collection allBooks;

@Override
public Book getBook(BookTag tag) {
    for (Book book : allBooks) {
        if (tag == book.getTag()) {
            return book;
        }
    }

    return null;
}

【问题讨论】:

    标签: java collections


    【解决方案1】:

    请改用private Collection<Book> allBooks;

    看看What are Generics in Java?

    【讨论】:

    • 我不知道t know if I can change this part of the code, because I have the class with the sectors that I need to write the code. If there is any other way I会很高兴。
    猜你喜欢
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多