作者:手机用户2502922161 | 来源:互联网 | 2023-05-18 20:54
SoIhavemanycustomclassesarealsohavecustomclasesinsideofthemusingcomposition.所以我有很多自
So I have many custom classes are also have custom clases inside of them using composition.
所以我有很多自定义类,其中也有使用组合的自定义clases。
My custom classes have variables that change very frequently and I add them to HashSets. So my question is when I implement hashCode - what should I do for a class that only has private fields that constantly change?
我的自定义类具有非常频繁更改的变量,我将它们添加到HashSet。所以我的问题是当我实现hashCode时 - 对于只有私有字段不断变化的类,我该怎么做?
Here is an example of one custom class:
以下是一个自定义类的示例:
public class Cell {
protected boolean isActive;
protected boolean wasActive;
public Cell() {
this.isActive = false;
this.wasActive = false;
}
// getter and setter methods...
@Override
public int hashCode() {
// HOW SHOULD I IMPLEMENT THIS IF THIS custom object is constantly
// being added into HashSets and have it's private fields isActive
// and wasActive constantly changed.
}
// ANOTHER QUESTION Am I missing anything with this below equals implementation?
@Override
public boolean equals(Object object) {
boolean result = false;
if (object instanceof Cell) {
Cell otherCell = (Cell) object;
result = (this.isActive == otherCell.isActive && this.wasActive ==
otherCell.wasActive);
}
return result;
}
3 个解决方案