JAVA hashCode返回值是否就等于地址值?
我们用==进行比较对象的时候,默认对比的是对象的内存地址值。
System.out.println进行打印对象,如果对象没有重写toString的时候,默认打印的也是对象的地址值
public cliass Test1{
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
System.out.println("地址值:"a1);
System.out.println("地址值:"a2);
System.out.println("hashCode: "+a1.hashCode());
System.out.println("hashCode: "+a2.hashCode());
System.out.println(a1==a2);
}
}
输出结果
地址值:com.demo.crowd.A@a09ee92
地址值:com.demo.crowd.A@30f39991
hashCode: 168423058
hashCode: 821270929
false
重写hashCode,使两个实例的hashCode值相等,让后再用==进行比较时,是否会返回true?
public class A {
private Integer number1 = 1;
// 重写hashCode,让hashCode的值为1