【发布时间】:2019-11-03 14:41:54
【问题描述】:
我正在尝试为 HashSet 编写 getter,其中 Object 包含字符串和整数的多个属性。 对于存储在 HashSet 中的每个对象,Getter 应该只返回两个字符串字段的连接字符串,用逗号分隔。
我可以使用循环来编写它,这样并不难,但我想找到更短、更优雅和更聪明的解决方案。 我尝试使用 String.join(),但它不接受对象的 HashSet。 使用 Object.toString() 不是一个选项,因为 toString() 应该返回更多 Object 的属性,而这个 getter 应该只返回其中两个。
让我们想象一下具有 Book 对象和 Borrower 对象的简化库,其中 Borrower 借用的每一本书都存储在 Borrower 对象的 HashSet 中。
import java.util.HashSet;
public class Main{
public static void main(String []args){
Borrower john = new Borrower("John");
Book book1 = new Book("Title1", "Author1", "Isbn1", 100);
Book book2 = new Book("Title2", "Author2", "Isbn2", 200);
Book book3 = new Book("Title3", "Author3", "Isbn3", 300);
john.borrowBook(book1);
john.borrowBook(book2);
john.borrowBook(book3);
System.out.println(john.getBorrowed());
// It should print
// Title1, Author1
// Title2, Author2
// Title3, Author3
}
}
class Book {
String title;
String author;
String isbn;
int pageNum;
Book(String t, String a, String i, int p){
this.title = t;
this.author = a;
this.isbn = i;
this.pageNum = p;
}
public String getAuthor() { return author; }
public String getTitle() { return title; }
}
class Borrower {
String name;
HashSet <Book> onLoan = new HashSet<Book>();
Borrower(String n){
this.name = n;
}
public boolean borrowBook(Book b) {
return onLoan.add(b);
}
public String getBorrowed(){
if(onLoan.isEmpty())
return "No books borrowed";
else{
// It should return joined string of only title and author for every book in HashSet,
//title and author separated with coma, each object in new line, like "title, author \n"
return "---";
}
}
}
Borrower 的 getBorrowed() 应该返回 HashSet 中每本书的唯一标题和作者的连接字符串。
【问题讨论】:
-
为什么不在
Book中覆盖toString()以返回你想要的? -
因为我需要完整的内容 toString() 到别的东西,而编写全新的方法并不是优雅的解决方案
标签: java string join return hashset