package com.sample;
import java.util.HashMap;
class Student{
int id;
@Override
public int hashCode() {
return -1;
}
@Override
public boolean equals(Object obj) {
return false; // returning false
}
}
public class MainClass {
public static void main(String[] args) {
Student s1=new Student();
s1.id=123;
Student s2=new Student();
s2.id=456;
HashMap<Student,String> s=new HashMap<Student,String>();
s.put(s1, "One");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
s.put(s2, "Two");
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
s.put(s1, "Three");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println("after insert");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
}
}
OUTPUT
< s1 value > One < s1 hashcode > 79430
< s2 value > Two < s2 hashcode > 84524
< s1 value > Three < s1 hashcode > 80786814
after insert
< s1 value > Three < s1 hashcode > 80786814 //printing three for s1
< s2 value > Two < s2 hashcode > 84524 //printing two for s2
// Теперь, если мы изменим возвращаемый тип метода equals на true, выходные изменения и оба возвращают три в качестве вывода. Я не могу понять, почему вывод изменяется, если мы меняем возвращаемый тип метода equals. Пожалуйста, объясните в контексте метода bucket (HashMap) и equals.Почему выход изменяется, если мы изменим возвращаемое значение метода equals?
class Student{
int id;
@Override
public int hashCode() {
return -1;
}
@Override
public boolean equals(Object obj) {
return true; //returning true
}
}
public class MainClass {
public static void main(String[] args) {
Student s1=new Student();
s1.id=123;
Student s2=new Student();
s2.id=456;
HashMap<Student,String> s=new HashMap<Student,String>();
s.put(s1, "One");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
s.put(s2, "Two");
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
s.put(s1, "Three");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println("after insert");
System.out.println(" < s1 value > "+s.get(s1) + " < s1 hashcode > "+s.get(s1).hashCode());
System.out.println(" < s2 value > "+s.get(s2) + " < s2 hashcode > "+s.get(s2).hashCode());
}
}
OUTPUT-
< s1 value > One < s1 hashcode > 79430
< s2 value > Two < s2 hashcode > 84524
< s1 value > Three < s1 hashcode > 80786814
after insert
< s1 value > Three < s1 hashcode > 80786814 //printing three for s1
< s2 value > Three < s2 hashcode > 80786814 //printing three for s2
См. [Почему для карты используется метод equals для проверки ключей] (http://stackoverflow.com/questions/31860486/does-a-map-using-equals-method-for-key-checking-exists) –