【问题标题】:Call a method contained in the class that is the hashmap value (Java) [duplicate]调用包含在类中的方法,该方法是哈希图值(Java)[重复]
【发布时间】: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),但我觉得这并不是你真正想要的,对吧?
  • 我建议你了解forwhile循环。

标签: java collections hashmap call


【解决方案1】:

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

itemMap.values().forEach(LibraryItem::printDetails)

【讨论】:

    【解决方案2】:

    大概你只是在寻找......

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-01
      • 2020-05-02
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      相关资源
      最近更新 更多