There are several ways to traverse the HashMap collection

public class bianli {
    //There are several ways to traverse the HashMap collection
    public static void main(String[] args) {
        HashMap<Integer,String> map=new HashMap<>();
        map.put(1, "Matthew");
        map.put(2, "Mark");
        map.put(3, "Luke");
        map.put(4, "John");

    public static void bianlimethod1(HashMap<Integer,String> map){
        for (Integer key : map.keySet()) {
        for (String value : map.values()) {

    public static void bianlimethod2(HashMap<Integer,String> map){
        Iterator<Map.Entry<Integer,String>> iterator=map.entrySet().iterator();
        while (iterator.hasNext()){

    public static void bianlimethod3(HashMap<Integer,String> map){
        Set<Integer> keyset=map.keySet();
        for (Integer i : keyset) {

    public static void bianlimethod4(HashMap<Integer,String> map){

1. Interview question: How is the hash function in HashMap implemented? What other hash functions are implemented?
Do the hash operation for the hashCode of the key, unsigned right shift by 16 bits and then do the XOR operation.
There are also square method, pseudo-random number method and remainder method. All three are relatively inefficient. The unsigned right shift 16-bit XOR operation is the most efficient. As for how the bottom layer is calculated, we will explain it to you when we look at the source code below.

2. Interview question: What happens when the hashCode of two objects are equal?
A hash collision will occur. If the content of the key value is the same, the old value will be replaced. Otherwise, it will be connected to the back of the linked list. If the length of the linked list exceeds the threshold of 8, it will be converted to a red-black tree for storage.

3. Interview questions: When does hash collision occur and what is hash collision, how to solve hash collision?
A hash collision occurs whenever the hash code value calculated for the key s of two elements is the same. Before jdk8, a linked list was used to solve hash collisions. After jdk8, use linked list + red-black tree to solve hash collision.

4. Interview question: If two keys have the same hashcode, how to store key-value pairs?
The hashcode is the same, and the contents are compared through equals.
Same: the new value overwrites the previous value
Not the same: add a new key-value pair to the hash table

Posted by fractalvibes on Tue, 31 May 2022 12:16:22 +0530