hashCode的做用

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

  1. List里面是能够放重复元素的,而且是有序的code

  2. 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

相关文章
相关标签/搜索