import java.util.Collection;
import java.util.HashSet;
public class ReflectTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Collection collections = new HashSet();
ReflectPoint pt1 = new ReflectPoint(3,3);
ReflectPoint pt2 = new ReflectPoint(5,5);
ReflectPoint pt3 = new ReflectPoint(3,3);
collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt1);
System.out.println(collections.size());
}
}
public class ReflectPoint {
public int x;
public int 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;
final ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
当我没有重写hashCode方法,集合长度为3
当我重写了hashCode方法,集合长度为2
我想请大家帮我总结一下hashCode方法的用途 |