ArrayList is one of the most used Collections in java. It is a dynamic array which means its size can increase automatically as more elements are added to it. Let us see how to create an arraylist:
ArrayList<Integer> arrList = new ArrayList<Integer>();
We need to give the object type within angle brackets which tells the type of elements stored in the arraylist.
Important points about ArrayList :-
- As elements are added the size of ArrayList also increases.
- ArrayList is present in java.util package.
- It implements List interface.
- We can also specify the initial size of the ArrayList while calling its constructor.
- Multiple null values can be inserted in arraylist.
- The order in which values are inserted in arraylist is maintained.
Let us look at an example code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Tech4Humans {
public static void main(String[] args) {
// ArrayList initialization without specifying the initial size
ArrayList<Integer> arrList1 = new ArrayList<Integer>();
arrList1.add(20);
arrList1.add(30);
System.out.println("arrayList1 = "+arrList1);
// ArrayList initialization without specifying the initial size
ArrayList<Integer> arrList2 = new ArrayList<Integer>(3);
arrList2.add(20);
arrList2.add(30);
arrList2.add(40);
arrList2.add(50);
arrList2.add(60);
System.out.println("arrayList2 = "+arrList2);
// ArrayList object assigned to List type reference variable
List<String> arrList3 = new ArrayList<String>();
arrList3.add("hello");
arrList3.add("world");
System.out.println("arrayList3 = "+arrList3);
// for loop to print the arrayList
System.out.print("\nArraylist print using for loop = ");
for(int i=0; i<arrList2.size(); i++) {
System.out.print(arrList2.get(i)+" ");
}
// for each loop to print the arrayList
System.out.print("\nArraylist print using for each loop = ");
for(Integer temp:arrList2) {
System.out.print(temp+" ");
}
// using Iterator to print arrayList
System.out.print("\nArraylist print using iterator = ");
Iterator<Integer> iter = arrList2.iterator();
while(iter.hasNext()) {
System.out.print(iter.next()+" ");
}
}
}
Output
arrayList1 = [20, 30]
arrayList2 = [20, 30, 40, 50, 60]
arrayList3 = [hello, world]
Arraylist print using for loop = 20 30 40 50 60
Arraylist print using for each loop = 20 30 40 50 60
Arraylist print using iterator = 20 30 40 50 60
Let us see what is the default size of ArrayList when it is created.