如何判斷兩個對象是否徹底相等

 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 }

 

運行結果:java

cheakObjIsEqual.Stu@f87ecac
cheakObjIsEqual.Stu@f87ecac

於是當內容徹底相同時,new Stu並不會分配另外空間,猜測hashCode決定了new運算是否會分配新空間this

驗證猜測:把equals方法註釋掉spa

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));
	}
}

  運行結果:code

cheakObjIsEqual.Stu@f87ecac
cheakObjIsEqual.Stu@f87ecac

修改輸入的信息爲:blog

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 }

運行結果:hash

cheakObjIsEqual.Stu@36962eb
cheakObjIsEqual.Stu@f87ecac

結果應該是hashCode決定了new運算是否會分配新的空間class

相關文章
相關標籤/搜索