I tried to do this

ArrayList<String> a=new ArrayList<String>(2);

Though i have specified a limit of 2 on the collection, i am able to add more. If this is general about Collections, is there any Collection which sets a limit and strictly follows it ?

6 Years
Discussion Span
Last Post by daudiam

Check the API of ArrayList. Never assume that classes and methods do what you think they do. The argument you have specified is the initial capacity of the ArrayList, not the size.

Check the constructors of the ArrayList class.

From the API:

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

Every time you add an element, the size of the list increases. When the size reaches its initial capacity, the list increases its capacity by a default value. Then you keep on adding elements and if you reach again its capacity, it will again increase.

Meaning that if you have the initial capacity to be small (in your case 2) and you add 1000 elements, then you will have many increases which takes time.
If you use a large initial capacity(2000) then the add method calls will be fast. Not many increases would be needed, but you would have wasted a lot of space.

In general for small applications you don't really care, so the default constructor would be enough to use.

Do you need to have the ArrayList have a max size?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.