调用包含在 class 中的方法,即 hashmap 值 (Java)

Call a method contained in the class that is the hashmap value (Java)

图书馆 Class:

旧版本 printAllItems()方法可以调用printDetails()方法对于存储在 ArrayList 中的每个元素:

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()方法不能调用printDetails() 存储在 hashMap 中的每个元素的方法:

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");
}

图书馆项目 Class:

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()

想必您只是在寻找...

for (LibraryItem libraryItem : itemMap.values()) {
    libraryItem.printDetails();
}

for (T varName : collection) {} 构造可用于遍历任何集合; itemMap.values()returns一个合集。它不是 ArrayList,但没关系。

您可以使用简单的 Collection#forEach 方法,该方法将简单地对 values()

的每个对象调用 printDetails
itemMap.values().forEach(LibraryItem::printDetails)