1

I have a small problem.

For example, I have ArrayList

ArrayList<Double> Temp1 = new ArrayList<>();

with size = 5 (0, 1, 2, 3, 4). I need to move the data by removing one value when comes the new value. For example, when Temp1.add(5) I have to get a result (1, 2, 3, 4, 5). Is it possible without using cycle?

Becuse In my app I have very big ArrayList (1000-15000 elements) that is filled from connected device with 5-10 items per sec. When I use the cycle "for" to retrieve last 50 items I lost productivity and receive from device 1-2 items per sec.

Jas
  • 3,207
  • 2
  • 15
  • 45
Vladimir
  • 25
  • 7
  • 2
    Can you switch to LinkedList? – Nyavro Dec 02 '15 at 06:19
  • You can replace by using this function: list.set( your_index, your_item ); – Dipesh Dhakal Dec 02 '15 at 06:21
  • Is the size fixed ? If so, you can use a fixed size array, and `start` and `end` indexes to implement a circular array .It will be more efficient than a LinkedList (if size is fixed). See https://en.wikipedia.org/wiki/Circular_buffer, https://www.youtube.com/watch?v=z3R9-DkVtds – André Oriani Dec 02 '15 at 06:36
  • @Nyavro, Thanks. I have not used before. I'll try! – Vladimir Dec 02 '15 at 06:56

4 Answers4

2

As @Nyavro mentioned in his comment, you can use a LinkedList which implements the Queue interface. Just add the new element to the tail and then pop the head.

List<Double> temp1 = new LinkedList<>();
temp1.add(5);
temp1.removeFirst();
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You can use set function for replacing some value for example, you need to remove 1 from Arraylist and change this to 100 then do it like this

Temp1.set(1,100);

Here 1 is index and 100 is value.

Amsheer
  • 7,046
  • 8
  • 47
  • 81
0

Do you always want to remove first element,Right.then you can try this, when you want to add new value,remove first by using,

Temp1.remove(0);
User_1191
  • 981
  • 2
  • 8
  • 24
0

From a duplicate question with this correct answer, here's a list of the datastructures you can use :

Community
  • 1
  • 1
thepace
  • 2,221
  • 1
  • 13
  • 21