[英]Retrieving hashmap values in java
我寫了下面的代碼來檢索哈希圖中的值。 但是它沒有用。
HashMap<String, String> facilities = new HashMap<String, String>();
Iterator i = facilities.entrySet().iterator();
while(i.hasNext())
{
String key = i.next().toString();
String value = i.next().toString();
System.out.println(key + " " + value);
}
我修改了代碼以包含SET類,並且效果很好。
Set s= facilities.entrySet();
Iterator it = facilities.entrySet().iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
沒有SET類,誰能指導我上面代碼中出了什么問題?
PS-我沒有太多的編程經驗,最近開始使用Java
您將調用next()
兩次。
嘗試以下方法:
while(i.hasNext())
{
Entry e = i.next();
String key = e.getKey();
String value = e.getValue();
System.out.println(key + " " + value);
}
簡而言之,您還可以使用以下代碼(該代碼還保留類型信息)。 使用Iterator
是Java 1.5之前的樣式。
for(Entry<String, String> entry : facilities.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " " + value);
}
問題是您要調用i.next()
來獲取密鑰,然后再次調用它來獲取值(下一個條目的值)。
另一個問題是您在其中一個Entry
上使用了toString
,這與getKey
或getValue
。
您需要執行以下操作:
Iterator<Entry<String, String>> i = facilities.entrySet().iterator();
...
while (...)
{
Entry<String, String> entry = i.next();
String key = entry.getKey();
String value = entry.getValue();
...
}
Iterator i = facilities.keySet().iterator();
while(i.hasNext())
{
String key = i.next().toString();
String value = facilities.get(key);
System.out.println(key + " " + value);
}
您在循環中多次調用i.next()
。 我認為這引起了麻煩。
您可以嘗試以下方法:
HashMap<String, String> facilities = new HashMap<String, String>();
Iterator<Map.Entry<String, String>> i = facilities.entrySet().iterator();
Map.Entry<String, String> entry = null;
while (i.hasNext()) {
entry = i.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " " + value);
}
String key;
for(final Iterator iterator = facilities.keySet().iterator(); iterator.hasNext(); ) {<BR>
key = iterator.next();<BR>
System.out.println(key + " : " + facilities.get(key));<BR>
for (Entry<String, String> entry : facilities.entrySet()) {<BR>
System.out.println(entry.getKey() + " : " + entry.getValue();<BR>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.