日期:2014-05-20 浏览次数:20740 次
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);
// }
}