我想在Java中创建一个方法,当它被调用时它会通过映射,查找输入的键并从集合中检索对象及其值的集合。从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);
}
我需要的是一种不需要参数的方法,通过迭代地图并打印出梳子萌发的地图键+图书信息(书名和yearPublished
到目前为止,我写了下面的:
/**
* 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));
}
}
但是,输出比较奇怪:
戈尔丁[书@ e8a4d45,书@ 4f196e15,书@ 69f8d3cd]肯尼斯·格雷厄姆 [书本@ 19d6f478,书@ 6f4bff88]
我如何能得到AR任何想法那么呢?我试图想出一种方法来检索书籍集合,它接受一个参数(地图关键字)并打印到标准输出地图关键字(作者姓名)以及他们编写的所有书籍(标题和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");
由威廉·戈尔丁写的书是:书@ e8a4d45,图书@ 4f196e15,>书@ 69f8d3cd]
我真的很感激,如果有人能帮助我。
在此先感谢。