equals与hashcode
java代码:
public class A {
private String name;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
System.out.println("equals");
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
System.out.println("hashcode");
return 1;
}
}
java代码
public void testHashA() {
A a = new A();
Set l = new HashSet(http://www.amjmh.com/v/);
for (int i = 0; i < 10; i++) {
a = new A();
a.setName(String.valueOf(i));
l.add(a);
}
System.out.println(l.size());
for (Iterator iter = l.iterator(); iter.hasNext();) {
A element = (A) iter.next();
System.out.println(element.getName());
}
}
输出为:
hashcode
hashcode
equals
hashcode
equals
hashcode
equals
hashcode
equals
hashcode
equals
hashcode
equals
hashcode
equals
hashcode
equals
hashcode
equals
1//只有一个元素
0//第一个元素
List、map加入对象时不会调用着两个方法
---------------------