1 class Stu{ 2 private String name = null; 3 private int age = 0; 4 5 public Stu(String name, int age){ 6 this.name = name; 7 this.age = age; 8 } 9 //覆写Object中的equals方法 10 public boolean equals(Object obj){ 11 if(this == obj){ 12 return true; 13 } 14 if(!(obj instanceof Stu)){ 15 return false; 16 } 17 Stu stu = (Stu)obj; 18 if((stu.age == this.age) && this.name.equals(stu.name)){ 19 return true; 20 } 21 return false; 22 } 23 //覆写Object中的hashCode方法 24 public int hashCode(){ 25 return this.name.hashCode() * this.age; 26 } 27 } 28 public class Main { 29 public static void main(String[] args){ 30 System.out.println(new Stu("Xiaobiqiang", 21)); 31 System.out.println(new Stu("Xiaobiqiang", 21)); 32 } 33 }
运行结果:
因而当内容完全相同时,new Stu并不会分配另外空间,猜想hashCode决定了new运算是否会分配新空间
验证猜想:把equals方法注释掉
class Stu{
private String name = null;
private int age = 0;
public Stu(String name, int age){
this.name = name;
this.age = age;
}
//覆写Object中的equals方法
/*
public boolean equals(Object obj){
if(this == obj){
return true;
}
if(!(obj instanceof Stu)){
return false;
}
Stu stu = (Stu)obj;
if((stu.age == this.age) && this.name.equals(stu.name)){
return true;
}
return false;
}
*/
//覆写Object中的hashCode方法
public int hashCode(){
return this.name.hashCode() * this.age;
}
}
public class Main {
public static void main(String[] args){
System.out.println(new Stu("Xiaobiqiang", 21));
System.out.println(new Stu("Xiaobiqiang", 21));
}
}
运行结果:
修改输入的信息为:
1 public class Main { 2 public static void main(String[] args){ 3 System.out.println(new Stu("Xiao", 21)); 4 System.out.println(new Stu("Xiaobiqiang", 21)); 5 } 6 }
运行结果:
结果应该是hashCode决定了new运算是否会分配新的空间