创建唯一的对象HashSet。
创建唯一的对象HashSet。
这个问题已经有答案了:
我创建了一个Person类和一个HashSet。如果我将同一个Person添加到HashSet中,它不知道该Person已经存在,会多次添加相同的Person。我需要覆盖哪个函数才能在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 allPeople = new List(); 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 hashset = new HashSet(); foreach(Person pers in allPeople) { hashset.Add(pers); } foreach(Person pers in hashset) { listBox1.Items.Add(pers.Name + ", " + pers.Age); } }
admin 更改状态以发布 2023年5月22日
首先,哈希集合如何判断两个对象是否相等。它不仅仅使用"Equals"方法来判断,还会使用"GetHashCode"方法比较两个对象的哈希码。
所以你需要重写GetHashCode方法,找到一种将你的Person对象映射到int值的方法。
例如,你可以使用"age + AsciiValue(name)"。
所以你只需要在你的person类中添加
public override int GetHashCode() { return age + AsciiValue(name); //i will leave the ascii value implementation to you }
,相同的person对象就不会再出现在同一个哈希集合中了。
原帖实现:
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; }