package com.franky.hashcode;
import java.util.Collection;
import java.util.HashSet;
/**
* @描述 关于hashCode的说明实例
* @作者 franky
* @日期 2014-12-30 下午9:37:42
*
*/
public class HashCodeTest {
/**
* @param args
*/
public static void main(String[] args) {
Collection<Point> points = new HashSet<Point>();
Point p1 = new Point(3, 3);
Point p2 = new Point(5, 5);
Point p3 = new Point(3, 3);
/**
* hashcode是通过类的某些属性计算得来的,在hashset集合中,hashcode用来计
* 算某个对象在集合中的存储位置的,通常是用这个hashcode对某个数取模运算,这样得
* 该对象应该存储在hashset集合中的具体位置,在查找该对象时候,仍然通过hashcode
* 进行位置计算,因此无须遍历整个集合即可查到该对象的位置,搜索速度快。
*/
/**
* 如果Point类不覆盖hashCode()和equals(Object obj)这两个方法,
* 那么p3对象是可以存入HashSet集合的,覆盖这两个方法后由于字段参与hashcode
* 的计算,所以计算的hasecode值是相等的,继而调用equals()方法进行对象的内容
* 判断,如果判断为true,那么代表这两个对象是同一个,继而HashSet集合不进行存储
* ,另外如果不是hash表结构的集合,就不会应用hashcode进行位置计算的
*
*/
points.add(p1);
points.add(p2);
points.add(p3);
points.add(p1);
//覆盖hashCode()和equals(Object obj)方法前,得到size为3,覆盖后为2
System.out.println(points.size());
//在对象加入hashset集合后,如果参与计算hashcode的某个字段值发生变化,那么集合
//在移除该对象的引用时,将无法搜索到,如果多个对象字段的值发生变化,可能引起内存泄露
p1.setX(5);
//移除失败
boolean remove = points.remove(p1);
System.out.println(remove);
System.out.println(points.size());
}
}
class Point{
private int x;
private 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;
Point other = (Point) 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 Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
hashcode的实例说明
最新推荐文章于 2022-04-24 15:35:19 发布