上記のコードでhashcode
関数が正しい方法で使用されているかどうか確認したいと思います。私はmap
に{1,2,3}の代わりにいくつかの奇妙なヌルと0の値があることに気づいた。ハッシュコード関数を持つクラス
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3};
Map<Row, Integer> map = map(array);
}
static class Row extends Object {
private int value;
private volatile int hashCode = 0;
public Row(int val) {
this.value = val;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Row at this point
Row row = (Row)obj;
return (value == row.value);
}
@Override
public int hashCode() {
final int multiplier = 7;
if (hashCode == 0) {
int code = 31;
code = multiplier * code + value;
hashCode = code;
}
return hashCode;
}
}
private static Map<Row, Integer> map(int[] array) {
Map<Row, Integer> arrayMap = new HashMap<Row, Integer>();
for (int i=0; i<array.length; i++)
arrayMap.put(new Row(array[i]), i);
return arrayMap;
}
}
私は上記のコードには欠陥がありません。 null値とゼロ値を表示するために使用したコードを含めて、そのコードの正確な出力を表示するのはなぜですか?なぜなら、これを[SSCCE](http://sscce.org/)に変えて、私たちができるようにするのはなぜでしょうか?それを自分で試してみませんか? –