dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Jun 18, 2021

Using Add() and Remove() ArrayList Methods in Java

We learned in a previous tip how to use the ArrayList Class to create an array in which you can adjust the elements in the array - something you cannot achieve with a traditional built-in array in Java. In this Java quick tip, we will learn how to add and remove elements in an array using the add() and remove() methods.

Before we begin, here is a refresher on how to use the ArrayList class:

// import the ArrayList class
import java.util.ArrayList;
 
// Create the Main function
 
public class Main {
            	public static void main(String[] args) {
 
//Creating an Arraylist object
            	ArrayList superHeroes = new ArrayList();
            	superHeroes.add("Big-Head Man!");
            	superHeroes.add("Developer Man!");
            	superHeroes.add("Lot-of-Legs-Woman!");
            	superHeroes.add("Captain Mustache!");
            	superHeroes.add("Wonder Wombat!");
//Printing elements of the ArrayList
            	System.out.println(superHeroes);
            	}
}

As you can see from the above code, we have actually already used the add() method when we created our ArrayList and then added elements to it.

If we want to remove items, we can do so using the remove() method:

// import the ArrayList class
import java.util.ArrayList;
 
// Create the Main function
 
public class Main {
            	public static void main(String[] args) {
 
//Creating an Arraylist object
            	ArrayList superHeroes = new ArrayList();
            	superHeroes.add("Big-Head Man!");
            	superHeroes.add("Developer Man!");
            	superHeroes.add("Lot-of-Legs-Woman!");
            	superHeroes.add("Captain Mustache!");
            	superHeroes.add("Wonder Wombat!");
//Printing elements of the ArrayList
            	System.out.println(superHeroes);
//Remove the first element in the Arraylist and re-printing it
            	superHeroes.remove(0);
    System.out.println(superHeroes);
            	}
}

When you run this code, you will see two lines of output. The first line shows the original list of elements in the ArrayList object. We then remove the element located at index 0 (the first position) and reprint the list to show that the element was removed. Here is the output you would receive if you ran this Java code:

[Big-Head Man!, Developer Man!, Lot-of-Legs-Woman!, Captain Mustache!, Wonder Wombat!]
[Developer Man!, Lot-of-Legs-Woman!, Captain Mustache!, Wonder Wombat!]
James Payne
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date