Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In this method, listNames, i am trying to print the details of the keys in the hashmap.

What I have tried:

Here is the class, and the method i am trying to but im doing it wrong at the moment.

Java
<pre>public class MapTester
{
    // instance variables - replace the example below with your own
    private HashMap<String, String> contacts;

    /**
     * Constructor for objects of class MapTester
     */
    public MapTester()
    {
        contacts = new HashMap<String, String>();

    }

    /**
     * Enter the given pair into the HashMap.
     * @param name A contact name (the key).
     * @param number The contact's phone number (as a string) (the value).
     */
    public void enterNumber(String name, String number)
    {
        contacts.put(name, number);
    }

    /**
     * Look up the given name in the map and return the associated number.
     * @param name The name to be looked up (the key)
     * @return The assoicated number, if any (the value).
     */
    public String lookUpNumber(String name)
    {
        return contacts.get(name);
    }

    /**
     * Print out the names (keys) in the map, one per line.
     */
    public void listNames()
    {
        for(String name: contact){
            System.out.println(contacts.keySet());
        }
    }
}
Posted
Updated 1-Dec-22 7:01am

1 solution

Java
for(String name: contact){
    System.out.println(contacts.keySet());

You cannot do that, contacts is not a list of Strings, it is a map of Key, Value pairs. So you need something like:
Java
for (String s : contacts.keySet())

I already gave you two lonks to the HashMap methods, you should also go to Java HashMap[^] and The Map Interface (The Java™ Tutorials > Collections > Interfaces)[^], which is the parent of the HashMap. Both of these pages give sample code and explanations.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900