SKay
SKay

Reputation: 147

Why do the same values get put into my LinkedHashMap Array?

I am using LinkedHashMap with an array. What is the way to 'put' and 'get' values?

In my LinkedHashMap<Integer, Integer[]> I have:

Key 1 -> integer array like {5,6,2,4}

Key 2 -> integer array, like {7,2,6,1}

.... goes on

Here is the code snippet I use to store values

// 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);
}
        

Is hParamVal.put correct?

the following code is to get data from LinkedHashMap

for (Integer key : hLoadSurveyParam.keySet()) {
  System.out.println(" KEY  # " + key);

  for (iCol = 0; iCol < iNoOfScalar; iCol++) {
    System.out.println(hParamVal.get(key)[iCol]);
  }
}

is hParamVal.get is correct of the above?

I am getting same value, because the last values get stored in iArryNoOfParam for all the keys!

Upvotes: 0

Views: 85

Answers (1)

Alex
Alex

Reputation: 5646

Bring this line Integer[] iArryNoOfParam = new Integer[iNoOfScalar]; into your for loop.

When you call put() you are storing the reference of the array in the LinkedHashMap. Since you are storing the same reference every time, you will only see the values that were set last. You want to store a new array reference for every key in the LinkedHashMap.

Upvotes: 3

Related Questions