-1

What is the best way to create some construction with exactly five elements and when I try to put another one to remove the firstone etc ?

Boris Pawlowski
  • 1,781
  • 4
  • 16
  • 22

6 Answers6

1

I would just recommend you an ArrayList It is very easy to Handle and the Remove/Add Operations are available

romaneso
  • 1,097
  • 1
  • 10
  • 26
0

Queue is the LIFO object you need.

  • If you are a Apache fan, you have CircularFifoQueue
  • If you are more into Guava, you have EvictingQueue
  • You can also do it yourself: (LinkedList is one implementation amongst others)

`

// Create
Queue q = new LinkedList();

// Insert 
void safeInsert(Queue q, Object elt) {
  if (q.size()>=5) {
    q.poll();
  }
  q.offer(elt);
}
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
0

The CircularFifoQueue provided by Apache Commons Collections does what you need.

Brent Worden
  • 10,624
  • 7
  • 52
  • 57
0

What you are asking for is called a circular buffer or ring buffer.

The Java library does not provide an implementation for you (confirmed, confirmed again), so you will have to write one yourself, or use a third-party library.

Community
  • 1
  • 1
Raedwald
  • 46,613
  • 43
  • 151
  • 237
0

I am not sure whether this is the "best solution", but it's quite simple and does exactly what you want:

List<Foo> list = new ArrayList<>();
...

list.add(item);
if(list.size()>5){
 list.remove(0);
}
achingfingers
  • 1,827
  • 5
  • 24
  • 48
0
public class MyArrayList extends ArrayList<Object>{

    private static final int MAX_SIZE = 5;

    @Override
    public void add(int index, Object object) {

        if(this.size() == MAX_SIZE)
            this.remove(0);
        super.add(MAX_SIZE -1, object);
    }

    @Override
    public boolean add(Object object) {

        if(this.size() == MAX_SIZE)
            this.remove(0);
        return super.add(object);
    }

    @Override
    public boolean addAll(Collection<? extends Object> collection) {
        throw new SomeException();
    }

    @Override
    public boolean addAll(int index, Collection<? extends Object> collection) {
        throw new SomeException();
    }

}