hashCode()方法

13 篇文章 0 订阅

如果两个元素的equals方法返回true,但他们的hashCode返回值不相等,HashSet将会把它们存储在不同的位置,但依然可以添加成功。

对于存放在Set容器中的对象,对应的类一定要重写equals和hashCode(Object obj)方法,以实现对象相等规则。

重写hashCode方法的原则:

  • 在程序运行时,同一个对象多次调用hashCode方法应该返回相同的值

  • 当两个对象的equals方法比较返回true时,这两个对象的hashCode方法的返回值也相等

  • 对象中用作equals方法比较的Field,都应该用来计算hashCode值

  • package com.xatu.集合;
    
    import java.util.HashSet;
    import java.util.Set;
    
    
    import org.junit.Test;
    
    class Point{
    	int x,y;
    
    	public Point(int x, int y) {
    		super();
    		this.x = x;
    		this.y = y;
    	}
    	 @Override
    	public int hashCode() {
    		 //100 200
    		return Integer.parseInt(x+" "+y);
    	}
    	@Override
    	public boolean equals(Object other) {
    		if (other instanceof Point) {
    			Point otherPoint = (Point) other;
    			if(this.x== otherPoint.x && this.y == otherPoint.y)
    			{
    				return true;
    			}
    		}
    		return false;
    		
    	}
    }
    public class hashCodeTest {
    	@Test
    	public void test() {
    		Point p1 = new Point(100, 200);
    		Point p2 = new Point(100, 200);
    		System.out.println(p1.equals(p2));
    		System.out.println(p1.hashCode());
    		System.out.println(p2.hashCode());
    		Set<Point> set = new HashSet<Point>();
    		set.add(p1);
    		set.add(p2);
    		System.out.println(set);
    	}
    }
    

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值