The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. 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.
Let us now see how we can initialize an ArrayList with add() method −
import java.util.ArrayList; import java.util.Collections; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(); myList.add(50); myList.add(29); myList.add(35); myList.add(11); myList.add(78); myList.add(64); myList.add(89); myList.add(67); System.out.println("Points\n"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)\n"+ myList); } }
Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending) [11, 29, 35, 50, 64, 67, 78, 89]
Let us now see another way to initialize ArrayList using the asList() method −
import java.util.*; public class Demo { public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(Arrays.asList(50,29,35,11,78,64,89,67)); System.out.println("Points\n"+ myList); Collections.sort(myList); System.out.println("Points (ascending order)\n"+ myList); } }
Points [50, 29, 35, 11, 78, 64, 89, 67] Points (ascending order) [11, 29, 35, 50, 64, 67, 78, 89]