【发布时间】:2021-07-01 17:53:19
【问题描述】:
库类:
旧版本 printAllItems() 方法可用于为 ArrayList 中存储的每个元素调用 printDetails() 方法:
private ArrayList<LibraryItem> itemList; // it declares an ArrayList of LibraryItem type
----
public void printAllItems()
{
System.out.println("Library Item\n");
for (LibraryItem libraryItem : itemList)
{
libraryItem.printDetails();
}
System.out.println("\n==================");
System.out.println("There are " + itemList.size() + " items");
}
新版本 printAllItems() 方法不能用于为 hashMap 中存储的每个元素调用 printDetails() 方法:
private Map<String, LibraryItem> itemMap; // it declares a HashMap of String and LibraryItem
----
public void printAllItems()
{
// values() can't be used to call printDetails() for each element
// it instead calls toString() method for each element, which is problematic for later
System.out.println("Library Item\n-----------------");
System.out.println(itemMap.values() + "\n");
System.out.println("\n=================");
System.out.println("There are " + itemMap.size() + " items");
}
LibraryItem 类:
protected void printDetails()
{
String loan = checkLoan(onLoan);
System.out.println(title + " with item code " + itemCode + " has been borrowed " + timesBorrowed + " times.");
System.out.println("This item is at present " + loan + " loan and when new cost " + cost + " pence.");
System.out.println();
}
新版本中如何调用printDetails()?
【问题讨论】:
-
你想要实现的是什么完全,因为看起来你可以做到
itemMap.values().forEach(LibraryItem::printDetails),但我觉得这并不是你真正想要的,对吧? -
我建议你了解
for和while循环。
标签: java collections hashmap call