I'm making use of HashSet's for algorithmic purposes, but I am having problems with the implementation of "custom objects". Doing some research it appears one should:
- Override Equals and GetHashCode (previous question here)
- Should not generate hashcodes with mutable objects (here yes it's Java, but I figured the implementation was close enough)
My Implementation:
//Simplified version of actual class with key components
class customObject {
public readonly uint column;
public readonly char row;
public customObject(uint column, char row) {
this.column = column;
this.row = row;
}
public override bool Equals(object obj) {
return obj is customObj && !ReferenceEquals(this, obj);
}
/*where uint column and char row are readonly. HashSet add is not called
until these variables are set with their lifetime value.*/
public override int GetHashCode() {
unchecked {
var hashCode = row.GetHashCode();
hashCode = (hashCode * 397) ^ column.GetHashCode();
return hashCode;
}
}
}
//somwhere else
HashSet<customObject> s = new HashSet<customObject>();
for(int i = 0; i < 10; i++) {
for(char c = 'A'; c < 'J'; c++) {
s.add(new customObject((uint)i,c));
}
}
Unfortunately, I am unable to add my custom object to the HashSet. As I can confirm the count
of items in the HashSet is 0 after attempting to add the object. Since there are no items in the set I suspect that I am missing something in the implementation, but have been unable to find a complete answer/tutorial regarding prepping custom objects for use in HashSets.