1、在講解hashCode以前先說下ArrayList和HashSet的區別java
看如下例子:ide
class PointR{ public PointR(int x, int y){ this.x=x; this.y=y; } 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; } } PointR p1 = new PointR(3,3); PointR p2 = new PointR(5,5); PointR p3 = new PointR(3,3); Collection collection = new ArrayList(); collection.add(p1); collection.add(p2); collection.add(p3); collection.add(p1); System.out.println(collection.size()); System.out.println("=============================="); Collection collection2 = new HashSet(); collection2.add(p1); collection2.add(p2); collection2.add(p3); collection2.add(p1); System.out.println(collection2.size()); 結果爲: 4 ============================== 3
區別:this
List裏面是能夠放重複元素的,而且是有序的code
Set裏面是不能存放相同的元素,而且是無序的對象
2、講解hashCode內存
接着上面的例子,咱們把PointR類的hashcode方法和euqals方法重寫下rem
class PointR{ public PointR(int x, int y){ this.x=x; this.y=y; } 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; PointR other = (PointR) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } PointR p1 = new PointR(3,3); PointR p2 = new PointR(5,5); PointR p3 = new PointR(3,3); Collection collection = new ArrayList(); collection.add(p1); collection.add(p2); collection.add(p3); collection.add(p1); System.out.println(collection.size()); System.out.println("=============================="); Collection collection2 = new HashSet(); collection2.add(p1); collection2.add(p2); collection2.add(p3); collection2.add(p1); System.out.println(collection2.size()); 結果爲: 4 ============================== 2
實現類的hashCode()方法,get
單一個set容器去接受這個類的對象時,會根據hashCode算出來的值給這個對象分配一個區域,之後查找這個對象的時候就到這個區域裏面去查找。hash
若是程序在運行的過程當中:修改了參與hashCode的字段的值,這個時候若是調用remove去移除這個對象的時候,hashcode會根據現有成員變量的值算出區域,在區域裏面查找並移除,這樣找不到原有的對象了。這樣就會形成內存溢出io