Remove item and play with ArrayList Size in Java

To delete an element, use the remove() method and refer to the index number:

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");
    mobiles.remove(0);
    System.out.println(mobiles);
  } 
}

To delete all the elements in the ArrayList, use the clear() method:

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");
    mobiles.clear();
    System.out.println(mobiles);
  } 
}

ArrayList Size in Java


To find out how many items are there in an ArrayList have, we have to use the size method:

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.size());
  } 
}

 

Keywords: