Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the main benefit of using HashMap in java?

In this Java project I'm looking at, I keep seeing code with HashMap, like so

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

Then later in the class:

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

What is the purpose of this code? I am foggy on the whole concept here.

like image 385
Caffeinated Avatar asked Jun 11 '12 00:06

Caffeinated


2 Answers

Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.

Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn't.

Answer to your edited question:

/** 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>();

Then later in the class:

//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);
like image 106
exception Avatar answered Nov 12 '22 16:11

exception


Main benefit of using HashMap in java? Probably speed. This Container splits its data to lot of "buckets" that contains only elements with same hashcode of key. That way when it needs to find some key-value pair, it dosesn't have to iterate over all its data, but only over elements with same hashcode in key as hashcode of searched key.

like image 38
Pshemo Avatar answered Nov 12 '22 18:11

Pshemo