黑马程序员技术交流社区

标题: 关于hashCode方法和hashSet集合的问题 [打印本页]

作者: crazy_primitive    时间: 2013-7-18 00:00
标题: 关于hashCode方法和hashSet集合的问题
本帖最后由 crazy_primitive 于 2013-7-18 13:14 编辑
  1. public class ReflectTest {
  2.         public static void main(String[] args) {
  3.                 Collection collections = new HashSet();
  4.                 ReflectPoint rpt1 = new ReflectPoint(4,5);
  5.                 ReflectPoint rpt2 = new ReflectPoint(7,2);
  6.                 ReflectPoint rpt3 = new ReflectPoint(4,5);
  7.                 collections.add(rpt1);
  8.                 collections.add(rpt2);
  9.                 collections.add(rpt3);
  10.                 collections.add(rpt1);
  11.                 System.out.println(collections.size());
  12.         }
  13.         }
  14.         public class ReflectPoint {
  15.         private int x;
  16.         public int y;
  17.         public ReflectPoint(int x, int y) {
  18.                 super();
  19.                 this.x = x;
  20.                 this.y = y;
  21.         }
  22. /*        @Override
  23.         public int hashCode() {
  24.                 final int prime = 31;
  25.                 int result = 1;
  26.                 result = prime * result + x;
  27.                 result = prime * result + y;
  28.                 return result;
  29.         }*/
  30.         @Override
  31.         public boolean equals(Object obj) {
  32.                 if (this == obj)
  33.                         return true;
  34.                 if (obj == null)
  35.                         return false;
  36.                 if (getClass() != obj.getClass())
  37.                         return false;
  38.                 ReflectPoint other = (ReflectPoint) obj;
  39.                 if (x != other.x)
  40.                         return false;
  41.                 if (y != other.y)
  42.                         return false;
  43.                 return true;
  44.         }
  45.         }

  46. //将hashCode()方法注释掉之前,System.out.println(collections.size())打印的是2
  47. //,这个好理解,可为什么注释掉之后打印的是3呢?
复制代码

作者: zms2100    时间: 2013-7-18 00:43
本帖最后由 zms2100 于 2013-7-18 00:45 编辑

1、因为一个很小细节的原因,注释复写的hashCode()方法后,添加元素到HashSet中时调用的还是hashCode方法不过是继承自Object的父类方法;       (在equals复写方法首行添加个打印语句就会发现,复写的equals方法没被调用过)。
2、要用equals比较就将复写的hashCode方法定义为return XXX(int型数值);3、另外: equals方法中的第一个判断if(this==obj)这个也是多余,==比较的是内存地址值,而rpt1与rpt3虽然相同,但是是不同对象,所以内存地址值也肯定不相同。







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2