Java Collection框架在Collection的生命周期中需要基于不变字段的equals()和hashCode()方法
2006-12-26 11:32
633 查看
Java Collection框架在Collection的生命周期中需要基于不变字段的equals()和hashCode()方法
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
public class CollectionRun {
public static void main(String[] args){
Set set=new HashSet();
Person p=new Person();
set.add(p);
System.out.println(set.contains(p));
p.setId("T");
System.out.println(set.contains(p));
}
}
class Person{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
if (this == o) return true;
if (o == null || !(o instanceof Person))
return false;
Person other = (Person)o;
// unsaved objects are never equal
if (id == null || other.getId() == null)
return false;
return id.equals(other.getId());
}
//将hashCode这个方法过行注释和不注释时运行的两种结果,考虑一下为什么?
public int hashCode() {
if (id != null) {
return id.hashCode();
} else {
return super.hashCode();
}
}
}
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
public class CollectionRun {
public static void main(String[] args){
Set set=new HashSet();
Person p=new Person();
set.add(p);
System.out.println(set.contains(p));
p.setId("T");
System.out.println(set.contains(p));
}
}
class Person{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
if (this == o) return true;
if (o == null || !(o instanceof Person))
return false;
Person other = (Person)o;
// unsaved objects are never equal
if (id == null || other.getId() == null)
return false;
return id.equals(other.getId());
}
//将hashCode这个方法过行注释和不注释时运行的两种结果,考虑一下为什么?
public int hashCode() {
if (id != null) {
return id.hashCode();
} else {
return super.hashCode();
}
}
}
相关文章推荐
- 【JAVA学习】java中==、equals()、hashCode()都和对象的比较有关,在java中这三者各有什么用处呢,即java中为什么需要设计这三种对象的比较方法呢?
- 【Java基础之重写equals、hashCode和compareTo方法】什么时候需要重写重写equals方法?为什么重写equals方法,一定要重写HashCode方法?
- 学习笔记-JAVA-考点10-什么情况下需要重写equals和hashcode()两个方法?
- 【原创】关于java对象需要重写equals方法,hashcode方法,toString方法 ,compareto()方法的说明
- JAVA Object对象(toString、equals、hashCode方法)、String类、StringBuffer、StringBuider、System、Runtime、Date、Mat
- java中hashCode方法与equals方法的用法总结
- 设计自己的基于Selenium 的自动化测试框架-Java版(1) - 为什么selenium还需要测试框架?
- 关于java的equals和hashcode方法
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- JAVA中的equals()和hashCode()方法
- java中equals()和hashCode()方法详解
- java :equals()和hashcode()方法的结合使用
- java中equals()方法与hashCode()方法的隐式调用时的约定详解
- Java 重写equals方法为什么还必须重写hashCode方法
- Java 中正确使用 hashCode 和 equals 方法
- java中hashCode方法与equals方法
- [Java] hashCode() 和equals()方法
- Java中的equals方法和hashcode方法
- HashMap什么时候重写hashcode和equals方法,为什么需要重写
- java equals()和hashcode()方法的理解