Search code examples
javacollectionshashmapcall

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


Library Class:

Old version printAllItems() method can be used to call printDetails() method for each element stored in the 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");
}

New version printAllItems() method can't be used to call printDetails() method for each element stored in the 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");
}

LibraryItem 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();
}

How can I call the printDetails() in the new version?


Solution

  • Presumably you're simply looking for...

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

    The for (T varName : collection) {} construct can be used to loop over any collection; itemMap.values() returns a collection. It's not an ArrayList, but that's fine.