hashCode()
オブジェクト ( ) の 1 つでオーバーライドを使用してinstance of A
、そのオブジェクトの一意の整数 ID を生成しています。一意性は、 ( instances of B
) 内のelements( ) のみに依存します。ArrayList
I
の定義は次の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
...
}
クラスの定義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
...
}
クラスの定義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
...
}
ご覧のとおり、すべてのオブジェクトを繰り返し処理しmyIterable
、最終的なhash
. 結果は、 の各bに依存しtype
、value
含まれています。私が気付いたのは、この値はプログラムの実行ごとに変化し、プログラムが重複したオブジェクトを作成しているため、問題が発生することです。myIterable
関連する列挙に対して hashCode() を実装できますが、これを処理する他の方法があるかどうか疑問に思っていました。以下は私の質問です:
- ランタイム間で等しい文字列の hashCode() を変更できますか?
- ランタイム間で同じ列挙値の hashCode() を変更できますか?
注: の実装は、 b inA.hashCode()
の順序に応じて異なるハッシュ値を返すことを認識していますが、これは望ましくありません。順序が重要でないように修正しています。myIterable