简体   繁体   English

创建一个打印ArrayList的方法,然后在另一个类中调用它

[英]Creating a method to print ArrayList, then calling it in another class

I've built an Arraylist in My class 'BookList', but I need it to print in another class. 我已经在“ BookList”类中​​构建了一个Arraylist,但是我需要它才能在另一个类中打印。

I think I may have to turn the printing of an Arraylist into a method, so then it can be called from a different class; 我想我可能必须将Arraylist的打印转换为方法,以便可以从另一个类中调用它; if I am wrong though, what else could I do to accomplish this? 如果我错了,我还能做些什么呢?

Below is my code, for reference. 下面是我的代码,以供参考。

import java.util.ArrayList;


public class BookList {

public static void main (String[] args){

    Book a = new Book();

    a.setTitle("Random ");
    a.setAuthor("Craig Robertson");
    a.setBookID("1847398812");
    a.setonLoan(false);
    a.setNumberofLoans(3);

    Book b = new Book();

    b.setTitle("The Last Refuge");
    b.setAuthor("Craig Robertson");
    b.setBookID("1471127753");
    b.setonLoan(false);
    b.setNumberofLoans(2);

    Book c = new Book();

    c.setTitle("The Bird That Did Not Sing");
    c.setAuthor("Alex Gray");
    c.setBookID("0751548278");
    c.setonLoan(true);
    c.setNumberofLoans(7);

    ArrayList<Book> BookList = new ArrayList<Book>();
    BookList.add(a);
    BookList.add(b);
    BookList.add(c);

    int count = BookList.size();
    System.out.println("Count: " + count);
    System.out.println("");

        for (Book  d : BookList){
            System.out.println(d);

    }   
  }
}

To go with this, I have the toString() method in my 'Book' class, so I could print all objects. 为此,我在'Book'类中具有toString()方法,因此可以打印所有对象。

An additional question: How would I print just the title and author of each object? 另一个问题:如何打印每个对象的标题和作者?

Create a static method in your Book class that will handle the display: Book类中创建一个静态方法来处理显示:

public static void showBooks(ArrayList<Book> books) {
    for (Book  d : Books){
        System.out.println(d); // calls the 'toString' method on each Book object
}

And call it this way from the main method: 并从main方法中以这种方式调用它:

ArrayList<Book> BookList = new ArrayList<Book>();
BookList.add(a);
BookList.add(b);
BookList.add(c);

Book.showBooks(BookList); // prints the books, one by one

How would I print just the title and author of each object? 如何仅打印每个对象的标题和作者?

You can choose to print the title and author only in the overriden toString method of your Book class: 您可以选择仅在Book类的重写 toString方法中打印titleauthor

@Override
public String toString() {
    // 'author' & 'title' are members of the 'Book' class
    return "Author: " + author + "- Title: " + title;
}

Override the BookList tostring method like so : 像这样重写BookList tostring方法:

public class BookList{
    @Override
    public String toString(){
        // Return some string here
    }
}

Then just use it normally. 然后只需正常使用即可。

System.out.println(myBookList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM