I am using overridden hashCode()
in one of my objects (instance of A
) to generate a unique integer ID for that object. The uniqueness depends only on elements(instances of B
) in a ArrayList
(I
).
Following is the definition of I
:
public class I extends ArrayList<B> {
//object of this class will iterate over this array
private B[] arrayOfB;
//other methods and variable to do something
...
}
Definition of class B
public class B {
private SomeEnum type;
private Object value; //this can be Integer, String, or some object defined by me
//getters for both private variables
...
}
Definition of class A
public class C implements Iterable {
private I myIterable;
@Override
public int hashCode() {
int result = 17;
for(B b: myIterable) {
result = 31 * result + b.getType().hashCode();
result = 31 * result + b.getValue().hashCode();
}
return result;
}
//other methods for this class
...
}
As you can see I iterate over all objects in myIterable
and construct the final hash
. The result depends on type
and value
contained in each b in myIterable
. What I have noticed is that this value changes with different runs of program and this creates a problem as the program is creating duplicate objects.
I can implement the hashCode() for the concerned enumerations but I was wondering if there is some other way to handle this. Following are my questions:
- Can the hashCode() of equal strings change between runtime?
- Can the hashCode() of same enum values change between runtime?
NOTE: I am aware that my implementation of A.hashCode()
will return different values of hash depending on order of b in myIterable
, which is not desired. I am fixing it so that order is not important.