我正在使用带有数组的LinkedHashMap
。 “投入”和“获取”价值的方式是什么?
在LinkedHashMap<Integer, Integer[]>
我有:
密钥1 - &gt;整数数组,如
{5,6,2,4}
密钥2 - &gt;整数数组,如
{7,2,6,1}
....继续
以下是我用来存储值的代码段
// has to store the data as order as it is received
LinkedHashMap<Integer, Integer[]> hParamVal = new LinkedHashMap<Integer, Integer[]>();
// temprory integer array to store the number as it is received
Integer[] iArryNoOfParam = new Integer[iNoOfScalar];
for (iRow = 0; iRow < iNoOfBlocks; iRow++) {
for (iCol = 0; iCol < iNoOfArrVal; iCol++) {
bBuffGenStr = Arrays.copyOfRange(BuffRecv, iStartLoc, iOffset);
GenDataVal oParamVal = dataStruct.readGenValue(bBuffGenStr);
bBuff4GenStr = oParamVal.getValue();
// store the integer array as received
iArryNoOfParam[iCol] = ByteBuffer.wrap(bBuff4GenStr)
.order(ByteOrder.LITTLE_ENDIAN).getInt();
iStartLoc = iOffset;
}
// store the array of Integer to every key
hParamVal.put(iRow, iArryNoOfParam);
}
hParamVal.put
是否正确?
以下代码是从LinkedHashMap
for (Integer key : hLoadSurveyParam.keySet()) {
System.out.println(" KEY # " + key);
for (iCol = 0; iCol < iNoOfScalar; iCol++) {
System.out.println(hParamVal.get(key)[iCol]);
}
}
hParamVal.get
是否正确?
我得到相同的值,因为最后的值存储在所有键的iArryNoOfParam
中!
答案 0 :(得分:3)
带上这条线
Integer[] iArryNoOfParam = new Integer[iNoOfScalar];
进入for
循环。
当您调用put()
时,您将在LinkedHashMap中存储数组的引用。由于每次都存储相同的引用,因此您只能看到最后设置的值。您希望为LinkedHashMap中的每个键存储一个新的数组引用。