14

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

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

4

2 回答 2

20

两者都提供对数据的键值访问。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);
于 2012-06-11T00:48:26.790 回答
6

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

于 2012-06-11T01:20:31.823 回答