Reputation: 10565
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
traverse()
.10
here.Any simple and nice solution?
Upvotes: 3
Views: 11916
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
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