JavaSE22–HashMap

Collection framework_HashMap

1. Overview

HashMap is a collection used to store Key-Value key-value pairs.
(1) HashMap stores data according to the hashCode value of the key. In most cases, its value can be directly located, so it has fast access speed, but the traversal order is uncertain.
(2) In HashMap, only one record with a null key is allowed, and there can be multiple records with a null value.
(3) HashMap is not thread-safe, that is, multiple threads are allowed to write HashMap at the same time at any time, which may lead to data inconsistency.

2. Features

The main features of HashMap are as follows:

  1. Thread-unsafe: HashMap is not a thread-safe container and is not suitable for multi-threaded environments. If you need to use Map in a multi-threaded environment, you can consider using ConcurrentHashMap or locking to ensure thread safety.
  2. Hash table implementation: HashMap is implemented using a hash table (Hash Table), which maps keys to the index positions of the hash table through a hash function, thereby achieving fast insertion, deletion and search operations.
  3. Elements are unordered: HashMap does not guarantee the order of elements. The position of elements in the hash table depends on the hash value of the key and the capacity of the hash table.
  4. Keys are not repeated: Keys in HashMap are not allowed to be repeated. If the key already exists when adding a key-value pair, the original value will be overwritten.
  5. Can store null: Both keys and values in HashMap can store null, but you need to pay attention to thread safety in concurrency situations.
  6. Efficient performance: Due to the use of hash tables, the time complexity of HashMap’s insertion, deletion and search operations is close to the constant level, so it has efficient performance.

In short, HashMap is a commonly used data structure. Its main features are efficient, unordered, and non-repeating keys, but it is not thread-safe. When using it, you need to select and design it according to the specific application scenario.

Three usage examples

The HashMap class is located in the java.util package and needs to be introduced before use. The syntax format is as follows:

import java.util.HashMap; //Introduce the HashMap class

In the following example, we create a HashMap object Sites, with a key of type Integer and a value of type String:

HashMap<Integer, String> Sites = new HashMap<Integer, String>();

Common methods of HashMap:
1. put(K key, V value): Store the key/value mapping into the Map collection.

2. get(Object key): Returns the value mapped by the specified key. If there is no value corresponding to the key, null is returned.

3. size(): Returns the number of data in the Map collection.

4. clear(): Clear the Map collection.

5. isEmpty(): Determine whether there is data in the Map collection, if not, return true, otherwise return false.

6. remove(Object key): Delete the data whose key is key in the Map collection and return its corresponding value.

7. values(): Returns data in Collection data type format composed of all values in the Map collection.

8. containsKey(Object key): Determine whether the specified key is included in the collection, and return true if included, otherwise return false.

9. containsValue(Object value): Determines whether the collection contains the specified value, returns true if included, otherwise returns false.

10. keySet(): Returns a Set consisting of all keys in the Map collection.

11. entrySet(): Convert each key-value of the Map collection into an Entry object and return a Set composed of all Entry objects.

1 Add elements

1.1 The HashMap class provides many useful methods. To add key-value pairs, you can use the put() method:

Example

//Introduce HashMap class
import java.util.HashMap;

public class worldTest {
    public static void main(String[] args) {
        // Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        //Add key-value pairs
        Sites.put(1, "hello");
        Sites.put(2, "world");
        Sites.put(3, "hi");
        Sites.put(4, "china");
        System.out.println(Sites);
    }
}

1.2 The following example creates a key of type String and a value of type String:

Example

//Introduce HashMap class
import java.util.HashMap;

public class worldTest {<!-- -->
    public static void main(String[] args) {<!-- -->
        // Create HashMap object Sites
        HashMap<String, String> Sites = new HashMap<String, String>();
        //Add key-value pairs
        Sites.put("one", "hello");
        Sites.put("two", "world");
        Sites.put("three", "hi");
        Sites.put("four", "china");
        System.out.println(Sites);
    }
}

2 Access elements

We can use the get(key) method to get the value corresponding to key:

Example

//Introduce HashMap class
import java.util.HashMap;

public class worldTest {
    public static void main(String[] args) {
        // Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        //Add key-value pairs
        Sites.put(1, "hello");
        Sites.put(2, "world");
        Sites.put(3, "hi");
        Sites.put(4, "china");
        System.out.println(Sites.get(3));
    }
}

3 Delete elements

3.1 We can use the remove(key) method to delete the key-value pair corresponding to key:

Example

//Introduce HashMap class
import java.util.HashMap;

public class worldTest {
    public static void main(String[] args) {
        // Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        //Add key-value pairs
        Sites.put(1, "hello");
        Sites.put(2, "world");
        Sites.put(3, "hi");
        Sites.put(4, "china");
        Sites.remove(4);
        System.out.println(Sites);
    }
}

3.2 To delete all key-value pairs, you can use the clear method:

Example

//Introduce HashMap class
import java.util.HashMap;

public class worldTest {
    public static void main(String[] args) {
        // Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        //Add key-value pairs
        Sites.put(1, "hello");
        Sites.put(2, "world");
        Sites.put(3, "hi");
        Sites.put(4, "china");
        Sites.clear();
        System.out.println(Sites);
    }
}

4 Calculation size

If you want to count the number of elements in a HashMap, you can use the size() method:

Examples

//Introduce HashMap class
import java.util.HashMap;

public class worldTest {
    public static void main(String[] args) {
        // Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        //Add key-value pairs
        Sites.put(1, "hello");
        Sites.put(2, "world");
        Sites.put(3, "hi");
        Sites.put(4, "china");
        System.out.println(Sites.size());
    }
}

5 Iterate HashMap

You can use for-each to iterate over the elements in a HashMap.

If you only want to get the key, you can use the keySet() method, and then you can get the corresponding value through get(key). If you just want to get the value, you can use the values() method.

Example

//Introduce HashMap class
import java.util.HashMap;

public class worldTest {
    public static void main(String[] args) {
        // Create HashMap object Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        //Add key-value pairs
        Sites.put(1, "hello");
        Sites.put(2, "world");
        Sites.put(3, "hi");
        Sites.put(4, "china");
        // Output key and value
        for (Integer i : Sites.keySet()) {
            System.out.println("key: " + i + " value: " + Sites.get(i));
        }
        // Return all value values
        for(String value: Sites.values()) {
          // Output each value
          System.out.print(value + ", ");
        }
    }
}

6 Copy a hashMap

Method: clone()

Example

public static void main(String[] args) {<!-- -->
    HashMap<String, String> map = new HashMap<>();
    map.put("A","1");
    map.put("B","2");
    map.put("C","3");
    Object clone = map.clone();
    System.out.println("original" + map);
    System.out.println("Copy" + clone);
}

7 Determine whether hashMap is empty

Method: isEmpty()

Examples

public static void main(String[] args) {<!-- -->
    HashMap<String, String> map = new HashMap<>();
    HashMap<String, String> map1 = new HashMap<>();
    map.put("A","1");
    map.put("B","2");
    map.put("C","3");
    boolean empty1 = map.isEmpty();
    boolean empty2 = map1.isEmpty();

    System.out.println(empty1);
    System.out.println(empty2);
}

8 Replace the value corresponding to the specified key in hashMap

Method: replace()

Examples

public static void main(String[] args) {<!-- -->
    HashMap<String, String> map = new HashMap<>();
    HashMap<String, String> map1 = new HashMap<>();
    map.put("A","1");
    map.put("B","2");
    map.put("C","3");
    System.out.println("Before replacing----" + map);
     map.replace("A", "100");
    System.out.println("After replacement----" + map);
}