hashcode的实例说明

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;
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值