如何在哈希图中打印所有键? [英] How do I print out all keys in hashmap?
本文介绍了如何在哈希图中打印所有键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试了解哈希图的工作方式,并且一直在研究小型电话簿程序.
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.
这是我的代码:
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));
}
}
推荐答案
在这里:
System.out.println(phoneBook.keySet());
这将使用Set.toString()方法在Map中打印一组键.例如:
This will printout the set of keys in your Map using Set.toString() method. for example :
["a","b"]
这篇关于如何在哈希图中打印所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文