Sunday, 1 November 2015

How to create an ArrayList



There are 3 constructors to create an ArrayList. For the first two construtors, an empty array list is created. The initial capacity is 10 unless it is explicitly specified by using the second constructor. When that space becomes too small, the list will increase by half of its size.

    public ArrayList()  
    public ArrayList (int initialCapacity)  

Note:- Unlike Vector, you cannot specify a capacity increment. For Sun’s reference implementation, the formula to increase capacity is newCapacity=(oldCapacity*3)/2+1. If you happen to call the constructor with a negative initial capacity, an IllegalArgumentException will be thrown.
Another constructor is copy constructor, creating a new ArrayList from another collection:
    
  public ArrayList(Collection c)  

You can not provide a custom initial capacity .Instead, the internal array will be sized at 10% larger than the collection size.

One of the easy way of creating ArrayList is

 String str[] = {“a”,”b”,”c”,”d”,”e”};  
 List list=new ArrayList(Arrays.as List(str));  



Happy Learning J

No comments:

Post a Comment