【问题标题】:Understaing Logic of HashMap in Java [duplicate]理解Java中HashMap的逻辑[重复]
【发布时间】:2015-07-25 16:27:28
【问题描述】:
import java.util.*;  
class TestCollection13{  
    public static void main(String args[]){  
        HashMap<Integer,String> hm=new HashMap<Integer,String>();  

        hm.put(100,"Amit");  
        hm.put(101,"Vijay");  
        hm.put(102,"Rahul");  

        for(Map.Entry m:hm.entrySet()){  
            System.out.println(m.getKey()+" "+m.getValue());  
        }  
    }  
}  

在上面的 HaspMap 程序中,我无法理解这个 for 循环背后的逻辑。为什么需要 Map.Entry 以及 entrySet() 的功能是什么? 请帮我解决这个问题。在此先感谢

【问题讨论】:

  • 你能把这个链接发给我吗?

标签: java dictionary collections hashmap


【解决方案1】:

for 循环遍历HashMap 中的所有条目。 entrySet() 将返回映射中的所有键值对。

Map.Entry 只是键值对的类型(就像String 是一个类型一样)。

【讨论】:

  • public class MyHash { public static void main(String a[]){ HashMap&lt;String, String&gt; hm = new HashMap&lt;String, String&gt;(); hm.put("first", "FIRST INSERTED"); hm.put("second", "SECOND INSERTED"); hm.put("third","THIRD INSERTED"); System.out.println(hm); Set&lt;String&gt; keys = hm.keySet(); for(String key: keys){ System.out.println("Value of "+key+" is: "+hm.get(key)); } } } 我也可以通过这种方式执行此程序。这两者有什么区别???。这里我们不使用 Map.Entry 作为键值对...
猜你喜欢
  • 2022-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 2019-01-30
相关资源
最近更新 更多