Java Hashmap, LinkedHashMap class extends HashMap, deals with the connected rundown of the sections in the map, while repeating a LinkedHashMap, every one of the components will be returned in the request in which components were embedded. Following is an example.
LinkedHashMapDemo.java
[java]package socket;
import java.util.*;
public class LinkedHashMapDemo {
public static void main(String args[]) {
// Create a hash map
LinkedHashMap lhm = new LinkedHashMap();
// Put elements to the map
lhm.put("Sam", new Double(2434.34));
lhm.put("Sachin", new Double(1234.22));
lhm.put("Lara", new Double(178.00));
lhm.put("David", new Double(999.22));
lhm.put("Holder", new Double(-199.08));
// Get a set of the entries
Set set = lhm.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 Sam's account
double balance = ((Double)lhm.get("Sam")).doubleValue();
lhm.put("Sam", new Double(balance + 1000));
System.out.println("Sam's new balance: " +
lhm.get("Sam"));
}
}[/java]
Here first create the hash map.
[java]LinkedHashMap lhm = new LinkedHashMap();[/java]
Put all the elements into the hashmap as follows.
[java] lhm.put("Sam", new Double(2434.34));[/java]
Get a set of the entries as follows.
[java] Set set = lhm.entrySet();[/java]
Output
When compile the code result will be as follows.
[java]Sachin: 1234.22
Lara: 178.0
David: 999.22
Holder: -199.08
Sam's new balance: 3434.34
[/java]
Difference between hashmap and hashtable
Hashtable and HashMap are utilized to store information in key and value form. Both will use hashing technique to store unique keys. The following are the some main difference.
- HashMap is non synchronized where as Hashtable is synchronized.
- Hahtable is a legacy class where as hashmap is new.
- HashMap uses iterator where as HashTable uses enumerator and iterator.