Is there a way to give size limit to TreeSet in Java Collections as we do for arrays? for example in arrays we do,
anArray = new int[10];
Is there a way to give size limit to TreeSet in Java Collections as we do for arrays? for example in arrays we do,
anArray = new int[10];
An array has a fixed length that must be specified when you create it.
A TreeSet
automatically grows as you add elements to it. You cannot set its size. You can only read it.
This threat can help you fixed size list in Java
Also, you can implement your own collection in order to add elements if your limit has not been reached
None of TreeSet's constructors specifies an initial size, it grows when elements are added. And there's no way to limit the maximum size of the data structure. Every time you add() a new element, you'd need to manually check if it has exceeded the maximum size allowed. You can specify this behavior by implementing a subclass that extends from TreeSet and overriding add(), addAll(), and the two constructors that receive a Collection as a parameter.
You can always make your own implementation. Here is an example to get you started; you may find that you wish to tweak it accordingly:
public class BoundedTreeSet<E> extends TreeSet<E> {
private final int limit;
public BoundedTreeSet(final int limit) {
super();
this.limit = limit;
}
public BoundedTreeSet(final int limit, final Collection<? extends E> c) {
super(c);
this.limit = limit;
}
public BoundedTreeSet(final int limit, final Comparator<? super E> comparator) {
super(comparator);
this.limit = limit;
}
public BoundedTreeSet(final int limit, final SortedSet<E> s) {
super(s);
this.limit = limit;
}
@Override
public boolean add(final E e) {
if (size() >= limit) {
return false;
}
return super.add(e);
}
@Override
public boolean addAll(Collection<? extends E> c) {
if (size() + c.size() >= limit) {
return false;
}
return super.addAll(c);
}
}
Here is an implementation of BoundedTreeSet
in Apache Solr, which keeps the biggest values when trying to insert into a "full" set :
http://lucene.apache.org/solr/4_6_0/solr-core/org/apache/solr/util/BoundedTreeSet.html
Maven artifact available here :
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-core</artifactId>
<version>4.6.0</version>
</dependency>
The closest you can come to an existing collection with capacity limits is a BlockingQueue. When adding items to the queue, you can specify a zero second (or very small) blocking timeout, so that an exception is thrown when the capacity is exceeded. For more details, see BlockingQueue.offer()