1 没有重写hashCode和equals的方法
package cn.xy.test;
public class Point1
{
private int x;
private int y;
public Point1(int x, int y)
{
super();
this.x = x;
this.y = y;
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
}
public class HashSetAndHashCode
{
public static void main(String[] args)
{
HashSet<Point1> hs1 = new HashSet<Point1>();
Point1 p11 = new Point1(3, 3);
Point1 p12 = new Point1(3, 3);
Point1 p13 = new Point1(3, 5);
hs1.add(p11);
hs1.add(p11);
hs1.add(p12);
hs1.add(p13);
System.out.println(hs1.size());
}
}
答案是3
2 重写hashCode和equals的方法
package cn.xy.test;
public class Point2
{
private int x;
private int y;
public Point2(int x, int y)
{
super();
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;
Point2 other = (Point2) obj;
if (x != other.x) return false;
if (y != other.y) return false;
return true;
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
}
public class HashSetAndHashCode
{
public static void main(String[] args)
{
HashSet<Point2> hs2 = new HashSet<Point2>(); Point2 p21 = new Point2(3, 3);
Point2 p22 = new Point2(3, 3); Point2 p23 = new Point2(3, 5);
hs2.add(p21);
hs2.add(p22);
hs2.add(p23);
System.out.println(hs2.size());
}
}
答案是2。p21和p22被认为是同一个对象。
3 没有重写hashCode的方法,但重写equals的方法
package cn.xy.test;
public class Point3
{
private int x;
private int y;
public Point3(int x, int y)
{
super();
this.x = x;
this.y = y;
}
@Override public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Point3 other = (Point3) obj;
if (x != other.x) return false;
if (y != other.y) return false;
return true;
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
}
public class HashSetAndHashCode
{
public static void main(String[] args)
{
HashSet<Point3> hs3 = new HashSet<Point3>();
Point3 p31 = new Point3(3, 3);
Point3 p32 = new Point3(3, 3);
Point3 p33 = new Point3(3, 5);
hs3.add(p31);
hs3.add(p32);
hs3.add(p33);
System.out.println(hs3.size());
}
}
可能是2,可能是3。因为根据内存地址算出的hashcode不知道是否在一个区域。 作者: 洪伟 时间: 2015-6-20 10:34
大赞楼主,谢谢分享作者: 安安安 时间: 2015-6-20 15:34
感谢分享。。作者: Nemo 时间: 2015-6-20 17:23
不错不错哈哈哈