1

I'm planning to do a small program that'll display a graph which will be updated a few times per second (maybe 100/200ms or so). The purpose is to plot over 1000 different values in the graph, somewhat like an XY plot.

When the array contains 1000 elements, I'd like to add a new element at the end, and in the process pushing all the other elements one step back. In essence, element 999 would become 998, and 998 would become 997... all the way to the first element, which would simply be thrown away. Does anyone have an example or a good algorithm for doing this, either with regular arrays, Vector, LinkedList or any other method?

My first thought would be to create a new array and copy the elements that I want to keep into the new one, throwing away say the first 100 elements. At this point, I'd add the new 100 elements at the end of the array, and keep repeating this process, but surely there must be a better way of doing this?

user1240989
  • 619
  • 1
  • 6
  • 5

3 Answers3

1

What you are asking about is called deque in the algorithmic world, i.e. double ended vector.

That is the class you will need.

Basically deque supports adding and removing elements from both the beginning and the end of the sequence.

EDIT Actually as I read through the documentation I was surprised to see that the sdk implementation of deque does not support direct indexing (I am used to using this structure in C++). So I kept on searching and found this answer, linking to this library, which might be of help for you.

Community
  • 1
  • 1
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Thanks, I'll try my hand at an implementation with ArrayDeque, as it has the methods I need for this project. Thanks again for the help. – user1240989 Apr 21 '12 at 21:15
1

Don't use an Array, the complexity of moving all elements is awful! The Java data structure that's best suited for this task is a Deque, I'd say.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0

I would keep on reusing the same array, and just restart at the beginning. To make myself more clear, suppose you have your array with elements 1..1000

int[] array =  new int[1000];
...
array = {1, 2, ...., 1000 };

If you now have to add element 1001, instead of trying to have an array {2, 3, ..., 1000, 1001}, I would go for an array {1001, 2, 3, ... 1000} and just keep track at which index my array actually starts. This replaces the difficulty of moving all elements by keeping a simple counter to the begin-index. To make it easy for yourself, you can introduce a utility method

private int startIndex = 1;//0 at the start
//I assume we are in the situation with array {1001, 2, 3, ..., 1000 }

public int convertIndex( int index ){
  return (index + startIndex) % 1000;
}
Robin
  • 36,233
  • 5
  • 47
  • 99