Question:
what is the difference between a map and a hashmap?
Duy Nguyen
2012-05-13 19:39:02 UTC
I'm new to CS, please give one or two examples.
Also, how would you iterate thru or sort a hashmap using Java's API ?

Any help is appreciated
Three answers:
godfatherofsoul
2012-05-14 12:52:30 UTC
java.util.Map is a generic Collections supertype for any key/value class. It is an interface that only describes behavior. HashMap is a specific implementation of Map that you can directly use. TreeMap is another Map implementation as is any other class that implements the java.util.Map interface.



Whenever you see someone referring to a Map generically, it usually means that the specific implementation isn't important or it is hidden from you.
?
2012-05-14 02:50:27 UTC
There is no difference between the objects. There is a difference in the interface you have to the object. In the first case, the interface is HashMap, whereas in the second it's Map. The underlying object, though, is the same.



The advantage to using Map is that you can change the underlying object to be a different kind of map without breaking your contract with any code that's using it. If you declare it as HashMap, you have to change your contract if you want to change the underlying implementation.



See toutorail http://www.java-samples.com/showtutorial.php?tutorialid=369

import java.util.*;

class HashMapDemo {

public static void main(String args[]) {

// Create a hash map

HashMap hm = new HashMap();

// Put elements to the map

hm.put("John Doe", new Double(3434.34));

hm.put("Tom Smith", new Double(123.22));

hm.put("Jane Baker", new Double(1378.00));

hm.put("Todd Hall", new Double(99.22));

hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries

Set set = hm.entrySet();

// Get an iterator

Iterator i = set.iterator();

// Display elements

while(i.hasNext()) {

Map.Entry me = (Map.Entry)i.next();

System.out.print(me.getKey() + ": ");

System.out.println(me.getValue());

}

System.out.println();

// Deposit 1000 into John Doe's account

double balance = ((Double)hm.get("John Doe")).doubleValue();

hm.put("John Doe", new Double(balance + 1000));

System.out.println("John Doe's new balance: " +

hm.get("John Doe"));

}

}
leigh t
2012-05-14 03:00:25 UTC
the same i guess.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...