Java hashcode方法?
一、Hash算法原理
当Set接收一个元素时根据该对象的内存地址算出hashCode,看它属于哪一个区间,在这个区间里调用equeals方法。
确实提高了效率。但一个面临问题:若两个对象equals相等,但不在一个区间,根本没有机会进行比较,会被认为是不同的对象。所以Java对于eqauls方法和hashCode方法是这样规定的:
1 如果两个对象相同,那么它们的hashCode值一定要相同。也告诉我们重写equals方法,一定要重写hashCode方法。
2 如果两个对象的hashCode相同,它们并不一定相同,这里的对象相同指的是用eqauls方法比较。
package com.yuan.test;
import java.util.HashSet;
class hashcode
{
private int x;
private int y;
public hashcode(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 Testhashcode
{
public static void main(String[] args)
{
HashSet hs1 = new HashSet();
hashcode p11 = new hashcode(3, 3);
hashcode p12 = new hashcode(3, 3);
hashcode p13 = new hashcode(3, 5);
hs1.add(p11);
hs1.add(p11);
hs1.add(p12);
hs1.add(p13);
System.out.println(hs1.size());
}
}
输出结果:
3
2、重写了hashcode方法
package com.yuan.test;
import java.util.HashSet;
import org.springframework.context.support.StaticApplicationContext;
class hashcode
{
private int x;
private int y;
public hashcode(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;
}
@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 (this.getClass() != obj.getClass()) return false;
hashcode other = (hashcode) obj;
if (x != other.x) return false;
if (y != other.y) return false;
return true;
}
}
public class Testhashcode
{
public static void main(String[] args)
{
System.out.println("before:"+hashcode.abc);
HashSet hs1 = new HashSet();
hashcode p11 = new hashcode(3, 3);
hashcode p12 = new hashcode(3, 3);
hashcode p13 = new hashcode(3, 5);
hs1.add(p11);
hs1.add(p11);
hs1.add(p12);
hs1.add(p13);
System.out.println(hs1.size());
}
}
输出结果:
2
p21和p22被认为是同一个对象。
3、 没有重写hashCode的方法,但重写equals的方法