public class HashSetTest {
public static void main(String[] args) {
PointTest pt1 = new PointTest(3, 3);
PointTest pt2 = new PointTest(3, 6);
PointTest pt3 = new PointTest(3, 3);
//向set集合中添加了4个元素
HashSet set = new HashSet();
set.add(pt1);
set.add(pt2);
set.add(pt3);
set.add(pt1);
//对象又两个参数, x,y,重写了hashCode 和equals, toString
class PointTest {
int x;
int y;
public PointTest(int x, int y) {
this.x = x;
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;
PointTest other = (PointTest) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}