HTML Java

Java Array List


Array List

ArrayList is concrete class which providing the implementation of List interface an object of this class is responsible to represent dynamic resizable array with initial capacity 10 elements.


Commonly used Constructor of ArrayList

  • public ArrayList()
  • public ArrayList(int capacity)
  • public ArrayList(Collection c)

List list =new ArrayList();

List.add(1);

So here autoboxing came into picture in 1.5 means before jdk 1.5 if we want to store primitive type of data then we have to convert 10 into object of class Integer type like this. And it adds element in insertion order and allowed duplicate Elements. By default capacity is 10.


int x=10;
Integer y =new Integer(x);
Now add into list
List.add(y);

List.add(3,5);

Add 3 postion 5 can provide index

Set method if we apply on it then it replace it the value at the index.

List.set(3,6);

If we again add on index 3 then it remove the data which at that index and add new one.

If you are trying to add more element beyond the capacity of this list then it starts increasing dynamically 50% of that older list what it does it keeps the data of that array size of 10 and 50 % of it and create new one and place all the data from that list into new one and start adding more element. We cannot give incremental factor here.


Example

package com.collection.programs;

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
public static void main(String args[]) {

List list = new ArrayList();
System.out.println(list);
System.out.println(list.size());
System.out.println(list.isEmpty());
list.add(10);
System.out.println(list.isEmpty());
list.add(3);
System.out.println(list.contains(10));
System.out.println(list);
list.add(2 ,5);
System.out.println(list);
list.set(2, 6);
System.out.println(list);
list.add(2, 8);
System.out.println(list);
List list1 = new ArrayList(list);
list1.add(10);
list1.add(4);
list1.add(3);
list1.add(5);

System.out.println(list1);
list1.removeAll(list);
System.out.println(list1);
list1.retainAll(list);
System.out.println(list);
}
}
Try it »