how to use arraylist in java

how to use arraylist in java

ArrayList is a part of the collection framework and is present in java. util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

  • ArrayList inherits the AbstractList class and implements the List interface.
  • ArrayList is initialized by size, however, the size can increase if collection grows or shrunk if objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases (seeĀ thisĀ for details).
  • ArrayList in Java can be seen as similar to a vector in C++.

Example

import java.util.ArrayList;

public class MyClass { 
  public static void main(String[] args) { 
    ArrayList cars = new ArrayList();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  } 
}

Output

[Volvo, BMW, Ford, Mazda]