Home > Net >  Hash map of multiple values
Hash map of multiple values

Time:01-20

I have a hash map of multiple values with the same key. I am looking for selecting a particular value of any index specified in a for loop and return the value. I have done the following but it is giving me errors Index out of bounds for length: event_actor is the key, x is the index of the values in a list

public static Message SelectReceivedMsg(int event_actor, double recv_time) {

    int x;
    for (x = 0; x < mBuffer.get(event_actor).size(); x  ) {
        if ((mBuffer.get(event_actor).get(x).getMsg_flag().equals("Tx")) && (mBuffer.get(event_actor).get(x).getMsg_Recvtime() == recv_time)) {
             mBuffer.get(event_actor).get(x);// get m from the received mBuffer
            found = true;
            break;
        }
        if (mBuffer.get(event_actor).get(x)==null) break;
    }
    return mBuffer.get(event_actor).get(x);
}

CodePudding user response:

HashMap in Java - implementation of Associative array and can't have two dublicate keys.

Mayby you need List<Pair<Integer, Object>> ?

CodePudding user response:

Consider your for statement :

  for (x = 0; x < mBuffer.get(event_actor).size(); x  ) {

If and when that loop completes “normally” (ie without hitting the break statements), then the value of x will be == mBuffer.get(event_actor).size() - in other words, 1 greater than the maximum index of mBuffer.get(event_actor).

So when the first thing you do after that loop is :

  return mBuffer.get(event_actor).get(x);

That x will be beyond the maximum index (ie “out of bounds”)

Something else caught my eye : It is good that you are testing for null with :

  if (mBuffer.get(event_actor).get(x)==null) break;

However, you want to move that check to BEFORE the first if :

  if ((mBuffer.get(event_actor).get(x).getMsg_flag().equals("Tx")) && …

Because that first if will be throwing the NullPointerException if that value is null before your second ‘`if`` checks for it !

  •  Tags:  
  • Related