在java中使用HashMap的主要好处是什么?

时间:2012-06-11 00:44:31

标签: java dictionary hashmap

在我正在看的这个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);

此代码的目的是什么?我对这整个概念都很模糊。

2 个答案:

答案 0 :(得分:19)

两者都提供对数据的键值访问。 Hashtable是Java中的原始集合类之一。 HashMap是新的集合框架的一部分,添加了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);

答案 1 :(得分:2)

在java中使用HashMap的主要好处是什么?可能速度快。此Container将其数据拆分为许多“桶”,其中仅包含具有相同哈希码键的元素。这样当它需要找到一些键值对时,它不必迭代它的所有数据,而只需要在键中具有相同哈希码的元素作为搜索键的哈希码。