你可以看一下这个代码:重写了equals() ,hashCode() import java.util.HashSet;public class SetTest3 { public static void main(String[] args) { HashSet set = new HashSet(); Student s1 = new Student("zhangsan"); Student s2 = new Student("zhangsan"); set.add(s1); set.add(s2); System.out.println(set); } }class Student { String name; public Student(String name) { this.name = name; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }}
这个跟c++中的指针作为成员变量时要重写拷贝构造函数一样。随便找本书看,都会仔细的说这个。
import java.util.HashSet;public class SetTest3
{
public static void main(String[] args)
{
HashSet set = new HashSet(); Student s1 = new Student("zhangsan");
Student s2 = new Student("zhangsan"); set.add(s1);
set.add(s2); System.out.println(set); }
}class Student
{
String name; public Student(String name)
{
this.name = name;
} public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
} public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null)
{
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
return true;
}}