JackWM
JackWM

Reputation: 10565

in Java, how to traverse a queue without destroying it, in a simple way?

E.g.

I have a queue

void someMethod() {

     history.add(new Sample(time, data));
     ...
     traverse(history);
}

void traverse(Queue<Sample> history) {
     for(int i=0; i<history.size(); i=i+10) {
         history.get(i)...  // ???
     }
}

class Sample {
  long time;
  double data;
}

The concerns are that

  1. I don't want to destroy this queue by calling traverse().
  2. Traverse the queue in a given step, say 10 here.

Any simple and nice solution?

Upvotes: 3

Views: 11916

Answers (4)

Natix
Natix

Reputation: 14257

If you just want to iterate, use a for-each loop or directly a for loop with an Iterator. This doesn't consume the queue.

If you need to iterate with a step, you can use this pattern. It works generally with any Iterable. Putting the skipping into a separate reusable method makes the code more clear than having two nested for loops.

public static void main(String[] args) {
    Queue<Sample> history = ...
    int step = 10;
    for (Iterator<Sample> it = history.iterator();
            it.hasNext(); skip(it, step - 1)) {
        // note that we skipped 1 less elements than the size of the step
        Sample sample = it.next();
        // stuff
    }
}

static void skip(Iterator<?> iterator, int count) {
    for (int i = 0; i < count && iterator.hasNext(); i++) {
        iterator.next();
    }
}

Upvotes: 4

JackWM
JackWM

Reputation: 10565

LinkedList<Sample> h = (LinkedList<Sample>) history;
for(int i=0; i < h.size(); i+=step) {
    h.get(i).memory ...
}

I just realized this approach, haven't tried it yet.

As nullptr pointed out, the condition for above code is that the Queue is implemented as a LinkedList. (which is my case: Queue<Sample> history = new LinkedList<Sample>();)

Upvotes: -1

zw324
zw324

Reputation: 27210

Queue implements Iterable, so a simple loop will traverse it:

for (Sample sample : history)

An Iterator is another way to do it, with more control (can destroy it if you want to), but more verbose.

Upvotes: 9

nullptr
nullptr

Reputation: 2284

for (Sample s : history)
    doStuff(s);

This is called the enhanced for-loop; you can read more about it here.

Upvotes: 10

Related Questions