之前一直有点模糊的概念 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;
}
}