【问题标题】:What is the main benefit of using HashMap in java?在 java 中使用 HashMap 的主要好处是什么?
【发布时间】:2012-06-13 23:17:37
【问题描述】:

在我正在查看的这个 Java 项目中,我不断看到带有 HashMap 的代码,就像这样

 /** imageID --> image map */
    Map<String,ImageIcon> imgs = new HashMap<String,ImageIcon>();

然后在课堂上:

// images 
loadImages();
actualImage = imgs.get(this.DEFAULT_IMAGE_ID);
JLabel label = new JLabel(actualImage);

这段代码的目的是什么?我对这里的整个概念一头雾水。

【问题讨论】:

  • @JigarJoshi - 谢谢你的链接,好点。经过我的编辑;我确实认为我的问题现在有点不同了

标签: java dictionary hashmap


【解决方案1】:

在 java 中使用 HashMap 的主要好处是什么?应该是速度吧。此容器将其数据拆分为许多“桶”,这些“桶”仅包含具有相同键哈希码的元素。这样,当它需要查找某个键值对时,它不必遍历其所有数据,而只需遍历键中哈希码与搜索键哈希码相同的元素。

【讨论】:

    【解决方案2】:

    两者都提供对数据的键值访问。 Hashtable 是 Java 中最原始的集合类之一。 HashMap 是新 Collections Framework 的一部分,随 Java 2 v1.2 添加。

    两者之间的主要区别在于,对 Hashtable 的访问是在表上同步的,而对 HashMap 的访问则不是。您可以添加它,但默认情况下它不存在。

    另一个区别是 HashMap 中的迭代器是故障安全的,而 Hashtable 的枚举器则不是。如果您在迭代时更改地图,您就会知道。

    而且,第三个区别是 HashMap 允许其中包含空值,而 Hashtable 不允许。

    回答您编辑的问题:

    /** imageID --> image map */
    //imageID - String. imgs is a map of imageID and ImageIcon. imageID is key. ImageIcon is value.
        Map<String,ImageIcon> imgs = new HashMap<String,ImageIcon>();
    

    然后在课堂上:

    //SEE INLINE COMMENTS
    // images 
    //No definition provided. May be putting values into the imgs map.
    loadImages();
    //this.DEFAULT_IMAGE_ID is some imageID. imgs.get gets the value for that imageID, which
    //is ImageIcon for that imageID. That is stored in actualImage variable.
    actualImage = imgs.get(this.DEFAULT_IMAGE_ID);
    //Creating a new JLabel with actualImage.
    JLabel label = new JLabel(actualImage);
    

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 2012-05-15
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      相关资源
      最近更新 更多