问题
I've built an Arraylist in My class 'BookList', but I need it to print in another class.
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; 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.
An additional question: How would I print just the title and author of each object?
回答1:
Create a static method in your Book
class that will handle the display:
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:
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:
@Override
public String toString() {
// 'author' & 'title' are members of the 'Book' class
return "Author: " + author + "- Title: " + title;
}
回答2:
Override the BookList tostring method like so :
public class BookList{
@Override
public String toString(){
// Return some string here
}
}
Then just use it normally.
System.out.println(myBookList);
来源:https://stackoverflow.com/questions/34192644/creating-a-method-to-print-arraylist-then-calling-it-in-another-class