我创建了一个类Person和一个HashSet。如果我将同一个人添加到 HashSet,它不知道这个人已经存在,它会多次添加同一个人。我需要覆盖什么函数才能在 HashSet 中只有唯一元素?
public class Person
{
public Person(int age, string name)
{
this.age = age;
this.name = name;
}
int age;
string name;
public int Age {
get { return age; }
set { age = value; }
}
public string Name {
get { return name; }
set { name = value; }
}
public override bool Equals(object obj)
{
var other = obj as Person;
if (other == null) {
return false;
}
return age == other.age && name == other.name;
}
}
void Button1Click(object sender, EventArgs e)
{
List<Person> allPeople = new List<Person>();
Person p = new Person(15, "John");
allPeople.Add(p);
p = new Person(22, "Michael");
allPeople.Add(p);
p = new Person(16, "Alex");
allPeople.Add(p);
p = new Person(22, "Michael");
allPeople.Add(p);
p = new Person(15, "John");
allPeople.Add(p);
HashSet<Person> hashset = new HashSet<Person>();
foreach(Person pers in allPeople) {
hashset.Add(pers);
}
foreach(Person pers in hashset) {
listBox1.Items.Add(pers.Name + ", " + pers.Age);
}
}
首先,哈希集如何知道 2 个对象是相等的。它不仅使用"等于"方法。它通过使用"GetHashCode"方法比较两个对象哈希代码。
所以你需要做的是覆盖GetHashCode,并找到一些方法将你的人映射到一个整数值。
例如,您可以执行"age + AsciiValue(name("。
所以你需要做的就是添加
public override int GetHashCode()
{
return age + AsciiValue(name); //i will leave the ascii value implementation to you
}
到你的 person 类,重复的人不应该再存在于同一个哈希集中
OP的实现:
int AsciiCode(string str) {
int sum = 0;
int len = str.Length;
for(int i = 0; i < len; i++) {
sum += str[i] * Convert.ToInt32(Math.Pow(2, i));
sum = sum % (Convert.ToInt32(Math.Pow(2, 31) - 1));
}
return sum;
}