我正在尝试在Java中创建一个方法,在调用时它会遍历地图,查找输入的密钥并从集合中检索对象集及其值。
对于上下文,这是一个包含两个类Book和Author的应用程序,其中作者拥有包含属性title和yearPublished的书籍集合。以下课程信息:
课本
public class Book
{
// instance variables
private String title;
private int yearPublished;
/**
* Constructor for objects of class Book
*/
public Book(String aTitle, int aYear)
{
this.title = aTitle;
this.yearPublished = aYear;
}
班级作者
public class Author
{
// instance variables
private Map<String, Set<Book>> bookSet;
/**
* Constructor for objects of class Author
*/
public Author()
{
bookSet = new HashMap<>();
}
我还创建了一个填充测试数据的方法,以便我可以测试其他方法:
/**
* This method can be used to populate test data.
*/
public void createTestData()
{
Set<Book> collection = new HashSet<>();
Book book1 = new Book("Lord of the Flies",1954);
Book book2 = new Book("Another Lord of the Flies",1955);
Book book3 = new Book("Jamaica Inn",1936);
collection.add(book1);
collection.add(book2);
collection.add(book3);
bookSet.put("William Golding",collection);
Set<Book> collection2 = new HashSet<>();
Book book4 = new Book("The Wind in the Willows",1908);
Book book5 = new Book("Oliver Twist",1838);
collection2.add(book4);
collection2.add(book5);
bookSet.put("Kenneth Grahame",collection2);
}
我需要的是一个不带参数的方法,遍历地图并打印出组合地图键+书籍信息(书名和年出版
到目前为止,我写了以下内容:
/**
* Prints out to the standard output the authors currently in the system and all the books written
* by them, together with the year it was published.
*/
public void printMap()
{
for (String key : bookSet.keySet())
{
System.out.println(key + " " + bookSet.get(key));
}
}
然而,输出很奇怪:
William Golding [Book @ e8a4d45,Book @ 4f196e15,Book @ 69f8d3cd] Kenneth Grahame [Book @ 19d6f478,Book @ 6f4bff88]
关于如何解决这个问题的任何想法?
此外,我正在尝试提出一种方法来检索书籍集合,该方法采用一个参数(地图键)并将标准输出打印到地图键(作者姓名)和所有书籍( title和yearPublished。这是我到目前为止所做的:
/**
* Searches through the map for the key entered as argument. If the argument is a key in the map, prints
* textual representation of its associated value, otherwise prints an output line announcing
* that the key is not present.
*/
public void printMapValue(String aKey)
{
System.out.println("The books written by " + aKey + " are: " + bookSet.get(aKey));
}
结果再次非常奇怪:
example.printMapValue("William Golding");
William Golding撰写的书籍有:[预订@ e8a4d45,Book @ 4f196e15,&gt; Book @ 69f8d3cd]
如果有人可以帮助我,我真的很感激。
提前致谢。
答案 0 :(得分:3)
您需要覆盖toString()
类的Book
方法才能获得可打印的字符串。
public String toString()
{
return title;
}
答案 1 :(得分:0)
只需覆盖toString()
课程中Object
班级的Book
方法。
e.g。
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", yearPublished=" + yearPublished +
'}';
}
答案 2 :(得分:0)