我想在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]
我真的很感激,如果有人能幫助我。
在此先感謝。