public class MyTest6
{
public static void main(String[] args)
{
Student student1 = new Student("zhangsan");
Student student2 = new Student("zhangsan"); HashSet hashSet = new HashSet(); System.out.println(student1.hashCode());
System.out.println(student2.hashCode());
System.out.println(student1.equals(student2)); System.out.println(hashSet.add(student1));
System.out.println(hashSet.add(student2)); System.out.println(hashSet);
}
}class Student
{
public String name; public Student(String name)
{
this.name = name;
} public int hashCode()
{
return this.name.hashCode();
}

/**
 * 这个是教程里的,运行后是对的
 */
// public boolean equals(Object obj)
// {
// if (this == obj)
// {
// return true;
// }
//
// if (null != obj && obj instanceof Student)
// {
// Student s = (Student) obj;
//
// if (name.equals(s.name))
// {
// return true;
// }
// }
//
// return false;
// }

/**
 * 这个是根据教程里的,结合自己想法,我就想直接传进来就是Student类型
 */
public boolean equals(Student student)
{
if (this == student)
{
return true;
}
if (name.equals(student.name))
{
return true;
} return false;
}

/**
 * 这个是写作业时候,自己最初写的
 */
// public boolean equals(Student student)
// {
// if (this == student)
// {
// return true;
// }
// return this.name.equals(student.name);
// }
}
求理解为什么不对?自己写方法时候就想传入的直接就是Student 类型存入集合时候教程说的先比较hashCode()值,再比较equals()自己写的方法在main中输出也能看到System.out.println(student1.equals(student2));输出是true啊,表示第一个zhangsan 加进入了第二个不该再加进去了。而换成教程的equals方法就可以了?还有为什么教程方法那里返回的是false,很费解啊,第一块那里不是本身,student1的name和student2的name比较,一样啊,这里是2个String的equals比较,我没理解错吧?那接着不是应该返回true了!!!为什么结果返回的是false,没搞懂
学习进度不是很快,刚看到集合框架中的接口,前一章的是List接口和两个实现类,这里刚讲到Set,请用通俗点的讲,直接读源码自己水平不足,先谢谢

解决方案 »

  1.   

    “求理解为什么不对?自己写方法时候就想传入的直接就是Student 类型.”   楼主这样写一个方法
          public boolean equals(Student student),没有覆写Object类的 public boolean equals(Object obj),相当于在类里定义了一个新的方法。
       这样,在添加第二个对象时,两个对象的hashCode一样,需要进一步用public boolean equals(Object obj)方法判断是否相等,而没有覆写的这个方法是判断 两个对象的地址是否相等(this == obj), 而这两个分别是两个对象的地址,所以认为不相等,就会放进hashset里。
        所以,关键是覆写Object类的 public boolean equals(Object obj)。
      

  2.   

    if (this == student)         {             return true;         } 
    这比较的是什么?
    是泛型类型么?
    貌似这样比较不合适。
      

  3.   


    检查下是不是自己本身,就是OBJECT的equals()的内容直接拿来用了。不知道什么是泛型,听教程提过但是还没学习到吧,这里比较的是两个引用,其实就是对象的地址,指向同一个地址就是同一个对象了。