java hashcode %_Java hashcode方法

Java hashcode方法?

一、Hash算法原理

当Set接收一个元素时根据该对象的内存地址算出hashCode,看它属于哪一个区间,在这个区间里调用equeals方法。

de882b9923a223a6814416ae5e167eb7.png

确实提高了效率。但一个面临问题:若两个对象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的方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值