Java hashcode方法?java
1、Hash算法原理算法
当Set接收一个元素时根据该对象的内存地址算出hashCode,看它属于哪个区间,在这个区间里调用equeals方法。spring
确实提升了效率。但一个面临问题:若两个对象equals相等,但不在一个区间,根本没有机会进行比较,会被认为是不一样的对象。因此Java对于eqauls方法和hashCode方法是这样规定的:ide
1 若是两个对象相同,那么它们的hashCode值必定要相同。也告诉咱们重写equals方法,必定要重写hashCode方法。this
2 若是两个对象的hashCode相同,它们并不必定相同,这里的对象相同指的是用eqauls方法比较。spa
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<hashcode> hs1 = new HashSet<hashcode>(); 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()); } }
输出结果:code
3orm
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<hashcode> hs1 = new HashSet<hashcode>(); 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被认为是同一个对象。