A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© crazy_primitive 中级黑马   /  2013-7-18 00:00  /  1301 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 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呢?
复制代码

评分

参与人数 1技术分 +1 收起 理由
杜光 + 1 每天提问并回答问题,是对知识的复习和积累.

查看全部评分

1 个回复

倒序浏览
本帖最后由 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虽然相同,但是是不同对象,所以内存地址值也肯定不相同。


评分

参与人数 1技术分 +1 收起 理由
杜光 + 1 每天提问并回答问题,是对知识的复习和积累.

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马