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"); //bianlimethod1(map); //bianlimethod2(map); //bianlimethod3(map); bianlimethod4(map); } public static void bianlimethod1(HashMap<Integer,String> map){ for (Integer key : map.keySet()) { System.out.println(key); } for (String value : map.values()) { System.out.println(value); } } public static void bianlimethod2(HashMap<Integer,String> map){ Iterator<Map.Entry<Integer,String>> iterator=map.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<Integer,String> mapEntry=iterator.next(); System.out.println(mapEntry.getKey()+"==="+mapEntry.getValue()); } } public static void bianlimethod3(HashMap<Integer,String> map){ Set<Integer> keyset=map.keySet(); for (Integer i : keyset) { System.out.println(i+"==="+map.get(i)); } } public static void bianlimethod4(HashMap<Integer,String> map){ map.forEach((key,value)->{ System.out.println(key+"---"+value); }); } }
Attached:
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