firesource
firesource

Reputation: 3

Adding arrays to a Queue in Java (pointer issue?)

I'm reading a sensor and want to get an average over an amount of messages, so i'm summing them, and i'm using a queue to remove the first measurement from the sum when a new measurement is added.

The problem is that the queue is not responding to array's as I expected, it somehow acts like a pointer, so when the original value is updated, the history is also changed with it.

import java.util.Queue;
Queue<int[]> q = new LinkedList();
int[] t = new int[1];
int len = 3;
void setup() 
{
  for(int i=0;i<len;i++){
    t[0]=len-i;
    q.add(t);
  }
  for(int i=0;i<len;i++){
    print(q.remove()[0]);print(';');
  }
}

Result of this code is: 1;1;1;

While expected result is: 3;2;1;

The question is, how do i properly add Arrays to Queues?

Upvotes: 0

Views: 573

Answers (1)

b.GHILAS
b.GHILAS

Reputation: 2313

You must instantiate the array in each iteration of the for loop, otherwise it's the same reference that will be modified

Queue<int[]> q = new LinkedList();
int len = 3;

void setup() {
    for (int i = 0; i < len; i++) {
        int[] t = new int[1];
        t[0] = 5 - i;
        q.add(t);
    }

    for (int i = 0; i < len; i++) {
        print(q.remove()[0]);
        print(';');
    }
}

Upvotes: 2

Related Questions