I tried to do this

ArrayList<String> a=new ArrayList<String>(2);
a.add("dss");
a.add("dsfs");
a.add("fsfs");

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 ?

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?

thanks a lot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.