-1

I have an ArrayList which can contain 3 elements. Now after adding first 3 elements whenever i want to add another elements it will be added in the last position(3) and the element of first position will be out of the list. For example:

 i add "a","b","c" in the list
               a
               b
               c
   then if i want to add "d" in the list               
               b
               c
               d

   then if i want to add "e" in the list 
               c
               d
               e

........so on

How can i do this in android??? Can anyone help??

  • possible duplicate of [Size-limited queue that holds last N elements in Java](http://stackoverflow.com/questions/5498865/size-limited-queue-that-holds-last-n-elements-in-java) – njzk2 Jul 16 '14 at 16:01

2 Answers2

2

You can accomplish the task by following code:

add.set(0,add.get(1));
add.set(1,add.get(0));
add.set(2,newElement);

after you have inserted first three element.

Rujul1993
  • 1,631
  • 2
  • 10
  • 10
  • 1
    in terms of complexity, this is terrible. also, it does not work (you probably means `add.get(2)`) – njzk2 Jul 16 '14 at 15:58
  • I dont understand what you are trying to say. Why wont it work? – Rujul1993 Jul 16 '14 at 16:07
  • What happens if the list has 4,5,6,7, ... 1000,.. items in the future? It is hard to maintain. – LHA Jul 16 '14 at 16:10
  • I answered the question as it was needed. I understand its not dynamic if he wants dynamic he can simply put a for loop with arraylist size and replace the integers.Anyway thanks for ur comments – Rujul1993 Jul 16 '14 at 16:12
  • @Rujul1993: simply try it. you'll that after the full example from the OP, your list contains `b, b, e`. – njzk2 Jul 16 '14 at 16:44
0

There's nothing in the stock API that I know of. You can easily create your own using one of the approaches described in this related question.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521