ArrayList
ArrayList is the subclass of List interface. ArrayList is an implementation of grow able or re sizable array data structure. It addition to that ArrayList also permits the random retrieval of elements.
ArrayList implements List as well as RandomAccess, Serializable, and Clonable interfaces.
RandomAccess interface is a marker interface.
Few important points about ArrayList
- Underlined data structure is grow able array or resizable array.
- Heterogeneous data elements are allowed.
- Null insertion is allowed.
- Duplicates are allowed.
- Insertion order is preserved.
Constructor in ArrayList
Constructs an empty list with an initial capacity
of 10.
Constructs a list containing the elements of the
specified collection, in the order they are returned by the collection's
iterator.
Constructs an empty list with the specified initial
capacity.
//ArrayListConsDemo.java
import java.util.*;
class ArrayListConsDemo
{
public static void main(String[] args)
{
ArrayList ar1=new ArrayList(); /* Create an empty ArrayList with default capacity 10 */
ArrayList ar2=new ArrayList(50); /* Creates an empty ArrayList with capacity 50 */
ArrayList ar3=new ArrayList(ar1); /* Creates a list containing elements of the specified collection */
}
}
//Sample program for ArrayList
import java.util.*;class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList ar1=new ArrayList();
ar1.add(10);
ar1.add("Hello");
ar1.add(new Object());
ar1.add(3,20);
System.out.println("Element at index 1 is "+ar1.get(1)+"\n");
System.out.println("List is empty ? "+ar1.isEmpty()+"\n");
System.out.println("Hello was removed from list "+ar1.remove("Hello")+"\n");
System.out.println("List contains Hello "+ar1.contains("Hello")+"\n");
ar1.clear();
System.out.println("List is empty ? "+ar1.isEmpty()+"\n");
}
}
Output of the above program
Scenarios when to choose ArrayList and when not to.
ArrayList is best choice
when our main function is retrieval of data. ArrayList could be worst choice if
our main function is insertion at middle or deletion from middle.
More details:
If we want to insert some element x at index 2, we have to perform shift operation of all the elements from index 2.
Think of the same problem when we have 1 million elements in the ArrayList and at some point we want to store element in the middle of the List. Number of shift operations performed in that case will be higher , which will decrease the performance of ArrayList.
No comments:
Post a Comment