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

标签 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);

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

最佳答案

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

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

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

而且,第三个区别是 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);

关于java - 在 java 中使用 HashMap 的主要好处是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973539/

相关文章:

java - Splunk Java 与 JUnit 的集成

java - 如何使用 JAXB XJC 从外部 XSD 文件生成类

ios - 在 map 标注气泡中加载远程图像时出现性能问题

python - 从列表列表生成 pandas 数据框

C映射数据结构

java - 想要存储 HashMap 吗?

java - 使用 rjb 将 ruby​​ hash 转为 java hashmap

java - 无法在 Glassfish 中获取 Oracle 连接

java - 什么时候应该阻止/订阅 Mono/Flux?

Python header unicode 到 dict