1. 程式人生 > >Object中的equal()方法詳細與"=="

Object中的equal()方法詳細與"=="

之前一直有點模糊的概念 equal()與==方法的區別!
package com.yangfan.equal;

public class Testequal {
	public static void main(String args[]) {
		Cat cat1 = new Cat(1, 2, 3);
		Cat cat2 = new Cat(1, 2, 3);

		System.out.println(cat2 == cat1);//本質上比較是比較內堆記憶體的指向引用是否相同!永遠是false
		System.out.println(cat2.equals(cat1));//在沒有重寫equal()方法之前:false,本質上也是呼叫了==來比較!
		                                       //重寫equal()後是:true;
		System.out.println("----------------");

		String s1 = new String("hello");
		String s2 = new String("hello");
		System.out.println(s2 == s1);//這個是指引用結果是:永遠是false
		System.out.println(s2.equals(s1));//String 重寫了equal()方法:true;預設重寫Date類s
	}
}

class Cat {
	private int color, height, weight;

	public Cat() {
	}

	public Cat(int color, int height, int weight) {
		super();
		this.color = color;
		this.height = height;
		this.weight = weight;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + color;
		result = prime * result + height;
		result = prime * result + weight;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Cat other = (Cat) obj;
		if (color != other.color)
			return false;
		if (height != other.height)
			return false;
		if (weight != other.weight)
			return false;
		return true;
	}

}