0

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!

Community
  • 1
  • 1
SKay
  • 147
  • 1
  • 22

1 Answers1

3

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.

Alex
  • 5,364
  • 9
  • 54
  • 69
  • @SKay Besides this, I think that this line `iStartLoc = iOffset;` doesn't make sense, since you'll be always copying the same portion of the `BuffTecv` array. I believe you should change that line to `iStartLoc += iOffset;`. – fps Jul 22 '15 at 14:25
  • Thanks it is working. So and array, iArryNoOfParam[1] can not be assign more than once?! – SKay Jul 22 '15 at 14:30
  • 1
    @Federico that is just code snippet! the issue is initializing array every time! – SKay Jul 22 '15 at 14:34