Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to set max size of a collection?

is there any way to set maximum size of collection in Java?

like image 940
Jarek Avatar asked Mar 04 '11 15:03

Jarek


People also ask

How do I limit the size of a list in Java?

size() method returns the size of the list as integer value. Integer max value is 2^31 and this value is equal to the 2147483647.

How do I find the size of a collection?

The Size of the different collections can be found with the size() method. This method returns the number of elements in this collection. This method does not take any parameters.

What is the maximum size of set in Java?

The actual practical size limit is probably somewhere in the region of Integer. MAX_VALUE (i.e. 2147483647, roughly 2 billion elements), as that's the maximum size of an array in Java.


1 Answers

You can do this:

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).

Reference:

  • Arrays.asList(T ...)

Or: using Guava, here's a static method that decorates an existing List with a maximum size

public static <T> List<T> setMaxSize(     final List<T> input, final int maxSize){      return new ForwardingList<T>(){          @Override         public boolean addAll(Collection<? extends T> collection){             return standardAddAll(collection);         }          @Override         public boolean addAll(int index, Collection<? extends T> elements){             return standardAddAll(index, elements);         }          public boolean add(T e) {             checkMaxSize();             return delegate().add(e);         }          @Override         public void add(final int index, final T e){             checkMaxSize();             delegate().add(index, e);         }          private void checkMaxSize(){             if(size() >= maxSize){                 throw new UnsupportedOperationException("Maximum Size "                     + maxSize + " reached");             }         }          @Override         protected List<T> delegate(){             return input;         }     }; } 

Since ForwardingXxx classes exist for all standard collection types, you can write yourself similar decorators for other collections as well.

Obviously this will only work if your client code uses the decorated collection. If you change the underlying collection you are screwed (just like the Collections.unmodifiableXXX methods)

Reference:

  • ForwardingList
like image 114
Sean Patrick Floyd Avatar answered Oct 06 '22 12:10

Sean Patrick Floyd