Results 1 to 4 of 4
  1. #1
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Rep Power

    Default Limiting size of ArrayList

    Hi guys,

    ArrayList can grow as the elements are added to it. Is there a was to define the upper limit of the ArrayList? For example, I want my ArrayList to throw some Exception when 101th element is added.

    Thanks for your time.

  2. #2
    CaptainMorgan's Avatar
    CaptainMorgan is offline Moderator
    Join Date
    Dec 2007
    NewEngland, US
    Rep Power


    You're probably looking for an API defined way to accomplish this, and I'm not certain there is one. Therefore, there shouldn't be anything wrong with using a standard control statement, ie: for loop. Soo...
    Java Code:
    1) for all elements up to and including 100 
        // ..... do something...
     // if attempt to add past 100
        // throw exception(which is kinda of pointless since that's what the control
        //  statement was for - only elements up to an including 100)
    Vote for the new slogan to our beloved Java Forums! (closes on September 4, 2008)
    Want to voice your opinion on your IDE/Editor of choice? Vote now!
    Got a little Capt'n in you? (drink responsibly)

  3. #3
    JAdmin is offline Member
    Join Date
    Jan 2008
    Rep Power


    Agree with Captain. You cannot limit the size of an ArrayList. You will have to come up with a mechanism to achieve this.

    You may subclass the ArrayList and implement your own code to prevent the size from growing beyond a limit.

    Something like

    public final class MyList extends ArrayList{

    public boolean add(Object o) throws Throwable{
    if(this.size() < 100)
    throw new MaxSizeReachedException("Limit reached");



    note : The above code is a kind of sudo code, just to give you an idea of what we meant.

    Hope this helps!
    Sincerely, Your friends at

  4. #4
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    New York
    Rep Power


    Yeah i would personally just do something like
    Java Code:
    ArrayList<String> list = new ArrayList<String();
    if(list.get(100) != null)  //If there exists a 101th element
         throw new ArrayIndexOutOfBoundsException();

Similar Threads

  1. ResultSet size
    By bugger in forum JDBC
    Replies: 18
    Last Post: 06-25-2011, 08:36 PM
  2. Replies: 2
    Last Post: 04-21-2008, 11:43 AM
  3. Limiting the capacity of a cell of JTable
    By rameshraj in forum Advanced Java
    Replies: 0
    Last Post: 03-24-2008, 03:20 PM
  4. File size
    By eva in forum New To Java
    Replies: 2
    Last Post: 12-19-2007, 10:27 AM
  5. Object size
    By kavithas in forum New To Java
    Replies: 0
    Last Post: 11-30-2007, 01:00 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts