java - 即使使用 toString() 方法,尝试打印 ArrayList 也会返回随机符号
问题描述
这是输出:
Customer@682a0b20
代码:
书类:
public class Book {
public String title;
public String author;
public int genre;
public Book(String title, String author, int genre) {
this.title = title;
this.author = author;
this.genre = genre;
}
public String getBookTitle() {
return title;
}
public String getBookAuthor() {
return author;
}
public int getBookGenre() {
return genre;
}
}
图书馆数据库类:
import java.util.*;
public class LibraryDatabase extends Book {
ArrayList<Book> bookDatabase;
public LibraryDatabase(String title, String author, int genre) {
super("1", "2", 3);
}
public ArrayList<Book> books(ArrayList<Book> bookDatabase) {
Book book1 = new Book("Harry Potter", "J.K. Rowling", 1);
bookDatabase.add(book1);
return bookDatabase;
}
public String toString() {
return ("Title: " + this.getBookTitle() + "Author: " + this.getBookAuthor() + "Genre: " + this.getBookGenre());
}
}
客户等级:
import java.io.*;
import java.util.*;
public class Customer {
public Customer() {
}
public void run() {
borrow();
}
public void borrow() {
titlesNow();
}
public void titlesNow() {
System.out.println(toString());
}
测试类:
import java.util.*;
import java.io.*;
public class Tester {
public static void main(String[] args) {
Customer customer = new Customer();
customer.run();
}
}
为什么输出是这样的?导致控制台为 ArrayList 打印类似内容的代码有什么问题?我搜索了很多问题,通常看起来问题与没有 toString() 方法有关。但是我在扩展 Book 类的 LibraryDatabase 类中有这个。所以有什么问题?
解决方案
如果您只想打印列表,您的课程必须看起来像这样。
书
public class Book {
public String title;
public String author;
public int genre;
public Book(){}
public Book(String title, String author, int genre) {
this.title = title;
this.author = author;
this.genre = genre;
}
public String getBookTitle() {
return title;
}
public String getBookAuthor() {
return author;
}
public int getBookGenre() {
return genre;
}
@Override
public String toString() {
return ("Title: " + this.getBookTitle() + "Author: " + this.getBookAuthor() + "Genre: " + this.getBookGenre());
}
}
图书馆数据库
public class LibraryDatabase extends Book {
List<Book> bookDatabase = new ArrayList<>();
public LibraryDatabase() {
super();
}
public List<Book> books() {
Book book1 = new Book("Harry Potter", "J.K. Rowling", 1);
bookDatabase.add(book1);
return bookDatabase;
}
}
顾客
public class Customer {
public Customer() {
}
public void run() {
borrow();
}
public void borrow() {
titlesNow();
}
public void titlesNow() {
LibraryDatabase library = new LibraryDatabase();
library.books().forEach(System.out::println);
}
}
我不知道您为什么必须从 Book 扩展图书馆数据库,以及为什么您在 Customer 中有三个方法相互调用以打印列表。此外,我不知道您是否想从不同的类中获取相同的列表,如果是这样,您必须实现单例模式。
推荐阅读
- r - 使用来自另一个 xts 对象的数据更新一个 xts 时间序列对象
- c# - Unity - 拖动停止后继续物体惯性?
- hyperledger-fabric - 如果使用 docker swarm 部署网络,如何确保超级账本结构中的数据持久性?
- javascript - 如何计算来自多个嵌套对象的特定值的对象数量?
- python - 在pyglet中设置鼠标光标
- reactjs - Auth0 登录演示在刷新时返回 400 并将我注销
- mysql - MYSQL 使用 group by 返回给定比较的日期输出
- mysql - 将外键列添加到现有表
- android - 启动android studio emulator 4.0.3(API 15)时出现黑屏
- java - 如何从适配器向列表视图添加两个按钮?