ArrayList in java

In java.util package the ArrayList class is found which is used to resize Array.
The main difference between an ArrayList and a built-in array in Java is that the syntax is also slightly different and the size of the array cannot be modified. Whenever you want to you can add and remove elements from an ArrayList.

Example

Create an ArrayList object called mobiles that will store strings:

import java.util.ArrayList; // import the ArrayList class 

ArrayList<String> mobiles = new ArrayList<String>(); // Create an ArrayList object


Add Items in Array
The ArrayList class has various useful methods.
 For example, to add elements to the ArrayList, by using the add() method

Example

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> mobiles = new ArrayList<String>();
    mobiles.add("Samsung");
    mobiles.add("Apple");
    mobiles.add("Nokia");
    mobiles.add("Sony");
    System.out.println(mobiles);
  }
}

 

Keywords: