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