Hello Friends,
I wrote a function yesterday, and defined an String array there. I defined it like,
String[] arr = null;
No error was shown by my IDE. I thought to move ahead. But when I tried to increase the size of my array, I was caught.
Now I learned the difference b/w Array & an Array List.
In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList.
An Array List
- The ArrayList class extends AbstractList and implements the List interface.
- An ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size.
- Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
Constructors of Array List
- ArrayList( )
- ArrayList(Collection c)
- ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity grows automatically as elements are added to an array list.
The following program will show How an Array Lists grows and How we define an Array.
import java.util.*;
/**
*
* @author Sulabh
*/
public class ArrayListDemo {
public static void main(String args[]){
// Creating an Array List
ArrayList arrlist = new ArrayList(); // Stating the initial size in not mandatory.
String[] arr = new String[2]; // We need to state the size of an Array.
System.out.println(“Size of Array List = “+arrlist.size());
System.out.println(“Size of String array = “+arr.length);
arrlist.add(“Sulabh”);
arrlist.add(“Pratik”);
arrlist.add(“Kuldeep”);
System.out.println(“Size of Array List = “+arrlist.size());
}
}
The output of the program will be :
Size of Array List = 0
Size of String array = 2
Size of Array List = 3
ensureCapacity() for ArrayLists :
Although the capacity of an ArrayList object increases automatically as objects are stored in it, you can increase the capacity of an ArrayList object manually by calling ensureCapacity( )
arrlist.ensureCapacity( int minimunCapacity );
By increasing its capacity once, at the start, you can prevent several reallocations later. Because reallocations are costly in terms of time, preventing unnecessary ones improves performance.
References :
1. How to use Array Lists in Java : http://www.ezdia.com/How_to_use_Array_List_in_Java/Content.do?id=1022
2. Array Lists in Java : http://www.ezdia.com/Array_List_in_Java/Content.do?id=1023
3. Differences b/w Array & ArrayLists : http://www.ezdia.com/Array_and_ArrayLists/Content.do?id=1024
