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被認爲是同一個對象。