HashMap and LinkedHashMap are two classes in Java Collections that implement the Map interface. They both store key-value pairs, where each key maps to a unique value. However, they have some differences in their implementation and behavior.
The main difference between HashMap and LinkedHashMap is the way they maintain the order of the entries. HashMap uses a hash table to store its entries and does not maintain any specific order. On the other hand, LinkedHashMap maintains the order of the entries as they were inserted using a doubly-linked list.
Here is an example of how to create a HashMap in Java:
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("third", 3);
hashMap.put("second", 2);
hashMap.put("first", 1);
for (String key : hashMap.keySet()) {
System.out.println(key + ": " + hashMap.get(key));
}
}
}
In this example, we create a HashMap and add three key-value pairs to it using the put() method. We then use a for loop to retrieve and print each key-value pair in the map. The order of the entries is not guaranteed and may vary on each run.
Here is an example of how to create a LinkedHashMap in Java:
import java.util.LinkedHashMap;
public class Example {
public static void main(String[] args) {
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("third", 3);
linkedHashMap.put("second", 2);
linkedHashMap.put("first", 1);
for (String key : linkedHashMap.keySet()) {
System.out.println(key + ": " + linkedHashMap.get(key));
}
}
}
In this example, we create a LinkedHashMap and add three key-value pairs to it using the put() method. We then use a for loop to retrieve and print each key-value pair in the map. The order of the entries is guaranteed to be the same as they were inserted.
In summary, the main difference between HashMap and LinkedHashMap in Java Collections is the way they maintain the order of the entries. HashMap does not guarantee any specific order, while LinkedHashMap maintains the order of the entries as they were inserted.