0

Is there any collection which allows me limit the number of elements allowed?

What I need is a collection with size of 5 elements, when this collection is full, a new element can be added, but the oldest element of this collection will be replaced for the new element.

hmrojas.p
  • 562
  • 1
  • 5
  • 15

3 Answers3

1

You can do this with majority of the Collections available in java.utils package. You can do this,sample for List Collection:

List<X> list = Arrays.asList(new X[desiredSize]);
// where X is any Object type (including arrays and enums,
// but excluding primitives)

The resulting list is modifiable, but not resizable (i.e. add(e) and remove(e) don't work, but set(index, e) does).

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
1

You can extend an old good ArrayList (or any other implementation which fits you the best).

import java.util.ArrayList;

public class LimitedCollection<E> extends ArrayList<E> {

    public static final int MAX_ELEMENTS = 2;

    @Override
    public boolean add(E e) {
        if (this.size() < MAX_ELEMENTS) {
            return super.add(e);
        } else {
            return false;
        }
    }
    }
Mirek Surma
  • 148
  • 1
  • 10
0

Either Guava EvictingQueue or Apache common-collections should do the job for you.

j3ny4
  • 442
  • 2
  • 8