我使用這個類作爲我的鑰匙與哈希映射對象鍵
public class Design {
private double[] factors = null;
public double[] getFactors() {
return factors;
}
public void setFactors(double[] factors) {
this.factors = factors;
}
public Design(double[] factors) {
this.factors = factors;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(factors);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Design))
return false;
Design other = (Design) obj;
if (!Arrays.equals(factors, other.factors))
return false;
return true;
}
我使用一個循環
public static void main(String[] args) {
Map<Design, Double> map = new HashMap<Design, Double>();
double[] dbl = new double[2];
for(int i=0; i<5; i++){
for(int j=0; j<2; j++){
System.out.println(j+i);
dbl[j] = j+i;
}
Design des = new Design(dbl);
map.put(des, Double.valueOf(i));
}
for(Design d: map.keySet()){
System.out.println(d.getFactors()[0] + "\t" + d.getFactors()[1]);
}
for(double d: map.values()){
System.out.println(d);
}
}
增加的值映射被覆蓋的hasCode()和equals()方法的HashMap問題在關鍵價值中。它顯示添加的最後一個鍵。
4.0 5.0
4.0 5.0
4.0 5.0
4.0 5.0
4.0 5.0
我在哪裏出錯?
感謝...的解決方法是添加DBL =新的雙[2];在將新值分配給數組之前... – 2012-01-09 22:59:15