今天做ehcache缓存时,需要从ArrayList中删除一个元素(自定义类型),调用了remove()函数,有点不放心remove函数的元素比较,网上搜了下remove方法的实现,见http://bmqnc.iteye.com/blog/773450,内部是用equals方法判断两个元素是否相同,突然又想到equals和 == 的区别,先回忆一下:
java里的equals方法和==的区别:
总的来说,没有重载equals方法的对象的equals方法和 == 都是比较其对象在堆内的空间地址。
其中,基本类型(int, char, bool……)不是对象,所以没有equals方法;
基本类型的包装类型(Integer,Boolean……),重载了equals方法,比较的是对象的成员变量值;
String类型也重载了equals方法,比较的是对象的串是否相等; 另外String还有常量池的概念,String s1="abc";String s2="abc"; 串"abc"分配内存是同一个,所以s1==s2是true;
重写equals方法
public boolean equals(Object obj) {
// a quick test to see if the objects are identical
if (this == obj)
return true;
// must return false if the explicit parameter is null
if (obj == null)
return false;
// if the class don't match,they can't be equal
if (getClass() != obj.getClass())
return false;
// now we know obj is non-null Employee
<span style="font-family:KaiTi_GB2312;">Goods </span>other = (<span style="font-family:KaiTi_GB2312;">Goods </span>) obj;
// test whether the fileds have identical values
return <span style="font-family:KaiTi_GB2312;">this.good_id==other.goods_id</span>;
}
参照 http://yuu1987.iteye.com/blog/1113191