您的位置:首页 > 其它

直接比较两个对象是否相等返回false和List中判断是否包含某个对象的问题

2014-09-07 19:11 567 查看
定义如下类

class GG{

private String name;

public GG(String name){

this.name=name;

}

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((name == null) ? 0 : name.hashCode());

return result;

}

}

再定义两个对象

GG g1=new GG("1");

GG g2=new GG("2");

如果直接进行比较:g1===g2将会返回false因为这样比较的是二者的引用。

这里我们现在需要重写equals 和 hashCode 方法;

class GG{

private String name;

public GG(String name){

this.name=name;

}

@Override

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((name == null) ? 0 : name.hashCode());

return result;

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

GG other = (GG) obj;

if (name == null) {

if (other.name != null)

return false;

} else if (!name.equals(other.name))

return false;

return true;

}

}

通常我们所用的String类型不用重写,可以直接用。

这两个方法可以通过myEclipse自动生成
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐