问题
I'm trying to learn how hashmaps work and I've been fiddling with a small phonebook program.
But I'm stumped at what to do when I want to print out all the keys.
here's my code:
import java.util.HashMap;
import java.util.*;
public class MapTester
{
private HashMap<String, String> phoneBook;
public MapTester(){
phoneBook = new HashMap<String, String>();
}
public void enterNumber(String name, String number){
phoneBook.put(name, number);
}
public void printAll(){
//This is where I want to print all. I've been trying with iterator and foreach, but I can't get em to work
}
public void lookUpNumber(String name){
System.out.println(phoneBook.get(name));
}
}
回答1:
Here we go:
System.out.println(phoneBook.keySet());
This will printout the set of keys in your Map using Set.toString() method. for example :
["a","b"]
回答2:
Maps have a method called KeySet with all the keys.
Set<K> keySet();
回答3:
You need to get the keySet from your hashMap and iterate it using e.g. a foreach loop. This way you're getting the keys which can then be used to get the values out of the map.
import java.util.*;
public class MapTester
{
private HashMap<String, String> phoneBook;
public MapTester()
{
phoneBook = new HashMap<String, String>();
}
public void enterNumber(String name, String number)
{
phoneBook.put(name, number);
}
public void printAll()
{
for (String variableName : phoneBook.keySet())
{
String variableKey = variableName;
String variableValue = phoneBook.get(variableName);
System.out.println("Name: " + variableKey);
System.out.println("Number: " + variableValue);
}
}
public void lookUpNumber(String name)
{
System.out.println(phoneBook.get(name));
}
public static void main(String[] args)
{
MapTester tester = new MapTester();
tester.enterNumber("A name", "A number");
tester.enterNumber("Another name", "Another number");
tester.printAll();
}
}
来源:https://stackoverflow.com/questions/26847081/how-do-i-print-out-all-keys-in-hashmap