Initialize an ArrayList in Java


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 −

Example

 Live Demo

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
"+ myList);       Collections.sort(myList);       System.out.println("Points (ascending order)
"+ myList);    } }

Output

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 −

Example

 Live Demo

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
"+ myList);       Collections.sort(myList);       System.out.println("Points (ascending order)
"+ myList);    } }

Output

Points
[50, 29, 35, 11, 78, 64, 89, 67]
Points (ascending order)
[11, 29, 35, 50, 64, 67, 78, 89]

Updated on: 20-Sep-2019

772 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements