1.equals()与‘==’的区别
== 比较的是对象的地址,equals可以通过重写 比较值
2.equals()和equalsIgnoreCase()的区别
equalsIgnoreCase()可以忽略大小写的比较
3.equals容易出现空指针异常,应使用确定有值的对象来调用equals
正例:"test".euqals(object)
反例:object.equals("test”)
4.重写equals 的同时建议也重写hashCode方法(若不重写 则可能出线数据不一致的情况 )
注意:同一对象在执行期间若已经存储在集合中,则不能修改影响hashCode值的相关信息,否则会导致内存泄露问题。
package org.cjr.test.testmodel;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
public class HashCodeTest {
public static void main(String[] args) {
Collection set = new HashSet();
Point p1 = new Point(1, 1);
Point p2 = new Point(1, 2);
p2.setX(10);
p2.setY(10); //修改要在 加入之前,否则会出现内存泄露的问题
set.add(p1);
set.add(p2);
set.remove(p2);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
System.out.println(object);
}
}
}
class Point {
private int x;
private int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public String toString() {
return "x:" + x + ",y:" + y;
}
}