日期:2014-05-20  浏览次数:20674 次

求理解,HashSet添加是加入判断自己写的equals为什么不对!

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,请用通俗点的讲,直接读源码自己水平不足,先谢谢