This is the ninth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Xiao Zhu: Did you encounter a strange thing today? What is it? Zhu: I put the object in the HashMap as the Key. Did the Key repeat? Did the Key repeat? There are two keys that are the same, right? Xiao Zhu: Yeah! Interesting, if you take the value, which will he return to you? Xiao Zhu: I haven’t tried this. Show me your code. Xiao Zhu: Ok.

code

Student

public class Student {

    private Integer id;
    
    private String name;

    // Get and set are omitted
    public Student(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null|| getClass() ! = o.getClass())return false;
        Student student = (Student) o;
        returnObjects.equals(id, student.id) && Objects.equals(name, student.name); }}Copy the code

Test

public class Test {
    
    public static void main(String[] args) {
        Student student1 = new Student(1."Xiao zhu");
        Student student2 = new Student(2."Daniel");
        HashMap<Student,String> hashMap = new HashMap<>();
        hashMap.put(student1,"Chicken dish");
        hashMap.put(student2,"Great spirit");
        // This method does not need to wear Student, so it is changed to verify that it is the same object
        updateValue(hashMap,student1);
        System.out.println(hashMap.size());
    }

    public static HashMap<Student,String> updateValue(HashMap<Student,String> hashMap,Student student){
        Student student1 = new Student(1."Xiao zhu");
        System.out.println(student1.equals(student));
        hashMap.put(student1,"New");
        returnhashMap; }}Copy the code

The results

true
3
Copy the code

In order to verify that the two objects are the same, I should use the updateValue method. I would have just passed HashMap

, but to verify I added a Student. Oh, that’s interesting. Why don’t you try to write a way to take out elements, such as:
,string>

getValue

public static void getValue(HashMap<Student,String> hashMap){
    Student student1 = new Student(1."Xiao zhu");
    System.out.println(hashMap.get(student1));
}
Copy the code

Xiao Zhu: I’ll try.

The output

null
Copy the code

Xiao Zhu: Why? I overwrote equals so they’re all equal, right? Why can’t you take it out! Understand the source HashMap.

public V put(K key, V value) {
    return putVal(hash(key), key, value, false.true);
}

/**
 * Implements Map.put and related methods.
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if(p.hash == hash && ((k = p.key) == key || (key ! =null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if(e.hash == hash && ((k = e.key) == key || (key ! =null && key.equals(k))))
                    break; p = e; }}if(e ! =null) { // existing mapping for key
            V oldValue = e.value;
            if(! onlyIfAbsent || oldValue ==null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
Copy the code

And the following paragraph.

public static void main(String[] args) {
    Student student1 = new Student(1."Xiao zhu");
    Student student2 = new Student(1."Xiao zhu");
    System.out.println(student1.equals(student2));
    System.out.println(student1.hashCode());
    System.out.println(student2.hashCode());
}
Copy the code

Xiao Zhu: I’ll run and have a look.

true
1456208737
288665596
Copy the code

If the two objects are not the same, then the two objects are not the same. If the two objects are not the same, then the equals method is not the same. If the equals method is not the same, then the equals method is not the same. Only the equals method is overridden and hashCode is not overridden, which violates the Java specification. In some cases, it does, but when you use hashsets, hashmaps, etc., it’s a problem. So don’t be lazy. Xiao Zhu: Yes.

Each reader according to this topic, can explore an interview question.

Student1. Equals (student2) // if true, hashMap.put(student1," char "); HashMap. Put (student2, "great spirit"); System.out.println(hashMap.size()); // What is it?Copy the code

Go test your friends.