使用 Get 方法仅提取数组列表中索引的某些部分

我有一个由不同类型组成的数组列表。我想使用数组列表中的get方法从指定的索引中只提取一个元素


public BookCollection() {

    collection = new ArrayList<Book>(10);

}


public void addbook(String title, String author, int year, double cost, boolean Available) {

    Book a = new Book(title, director, year, cost, Available);

    collection.add(a);

}

在上面的代码中,我想创建一个图书库,但在某些时候我只想要标题。


public static void main(String[] args) {

    BookCollection library = new BookCollection();

    library.addbook("Pride & Prejudice", "Jane Austen", 1801, 24.95, true);

    System.out.println(collection.get(0).toString())

}

然后我只想得到标题。所以在这种情况下,它会是傲慢与偏见。目前输出是“傲慢与偏见Jane Austen180124.95”但我希望它只是“傲慢与偏见”。


胡子哥哥
浏览 157回答 2
2回答

白板的微信

collection.get(0).getTitle()?

慕慕森

技嘉的回答是对的。您应该在 Book 类中为每个字段创建 getter 方法,以便您可以随时单独调用。您还应该检查 Java 规则和约定,在这种特殊情况下,变量和方法名称应该以小写字母开头,因此您应该从“Available”切换到“available”。大写字母用于类。我尝试了您的代码并找到了解决方案,希望它适合您:这是 BookCollection 类:public class BookCollection extends ArrayList<Book>{private static final long serialVersionUID = 1L;private ArrayList<Book> collection;public BookCollection() {&nbsp; &nbsp; this.collection = new ArrayList<Book>();}public void addbook(String title, String author, int year, double cost, boolean available) {&nbsp; &nbsp; Book a = new Book(title, author, year, cost, available);&nbsp; &nbsp; this.add(a);}public static void main(String[] args) {&nbsp; &nbsp; BookCollection library = new BookCollection();&nbsp; &nbsp; library.addbook("Pride & Prejudice", "Jane Austen", 1801, 24.95, true);&nbsp; &nbsp; System.out.println(library.get(0).isAvailable());}}这是 Book 类,带有 getter 和 setter:public class Book {private String name;private String author;private int year;private double cost;private boolean available;public Book(String name, String author, int year, double cost, boolean available){&nbsp; &nbsp; this.name = name;&nbsp; &nbsp; this.author = author;&nbsp; &nbsp; this.year = year;&nbsp; &nbsp; this.cost = cost;&nbsp; &nbsp; this.available = available;}public String getName() {&nbsp; &nbsp; return name;}public void setName(String name) {&nbsp; &nbsp; this.name = name;}public String getAuthor() {&nbsp; &nbsp; return author;}public void setAuthor(String author) {&nbsp; &nbsp; this.author = author;}public int getYear() {&nbsp; &nbsp; return year;}public void setYear(int year) {&nbsp; &nbsp; this.year = year;}public double getCost() {&nbsp; &nbsp; return cost;}public void setCost(double cost) {&nbsp; &nbsp; this.cost = cost;}public boolean isAvailable() {&nbsp; &nbsp; return available;}public void setAvailable(boolean available) {&nbsp; &nbsp; this.available = available;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java