FreeCode

Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

Array List Data Structures

Code Description:

Lists are similar to Arrays in how they store data sequentially. Array Lists are special in that they are able to expand in size during run-time, unlike standard Arrays. Array Lists are more efficient than Linked Lists when you need to retrieve elements in the list.

Array List Syntax:

ArrayList<String> arrayList = new ArrayList<String>();

Runnable Array List Example Code:

import java.util.ArrayList;

public class Demo {

    public static void main(String[] args) {
		
	ArrayList<String> arrayList = new ArrayList<String>();

	arrayList.add("Element1");
	arrayList.add("Element2");
	arrayList.add("Element3");
	arrayList.remove(0);

	for (int i = 0; i < arrayList.size(); i++) {
	    System.out.println(arrayList.get(i));
	}
		
    }
	
}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

Array List Output Image

Important Methods:

  • add() - adds a single element at the specified index to the list.
  • addAll() - adds all elements in a collection (array, another list, etc).
  • get() - retrieves the element at the specified index.
  • remove() - deletes the element at the specified index.
  • size() - returns the number of elements in the list.
  • clear() - removes all elements in the list.

Related Links:

For-each Loops Array Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures