【发布时间】:2017-05-09 16:59:18
【问题描述】:
我正在尝试在 Java 中创建一个方法,当调用它时,它将通过映射,查找输入的键并从集合中检索对象集及其值。
就上下文而言,这是一个具有两个类的应用程序,Book 和 Author,其中 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));
}
}
然而,输出相当奇怪:
威廉·戈尔丁 [Book@e8a4d45, Book@4f196e15, Book@69f8d3cd] 肯尼斯 格雷厄姆 [Book@19d6f478, Book@6f4bff88]
关于我如何解决这个问题的任何想法?
另外,我正在尝试提出一种检索书籍集的方法,该方法采用一个参数(地图键)并将地图键(作者姓名)和他们编写的所有书籍打印到标准输出(标题和年份。这是我到目前为止所拥有的:
/**
* 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");
威廉·戈尔丁写的书有:[Book@e8a4d45, Book@4f196e15, >Book@69f8d3cd]
如果有人可以帮助我,我将不胜感激。
提前致谢。
【问题讨论】: