Reputation: 3150
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];
Upvotes: 4
Views: 9079
Reputation: 2773
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>
Upvotes: 2
Reputation: 9337
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()
Upvotes: 0
Reputation: 236014
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.
Upvotes: 2
Reputation: 26502
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);
}
}
Upvotes: 2
Reputation: 14747
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
Upvotes: 3
Reputation: 838326
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.
Upvotes: 5