[Java] ArrayList class

less than 1 minute read

Use an ordinary array after deciding how many elements to store.


int r [] = new int[4]

r[0] = 88;
r[1] = 45;
r[2] = 34;
r[3] = 47;

However, if you don’t know the number of elements in advance but want to use an array, use Collection.

Example of using ArrayList class as one of collections

The following is the process of generating a random number less than 10 and storing it in ArrayList until 0 is output.


import java.util.ArrayList; // Import.
import java.util.Random;

public class PracticeList {
  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<Integer>(); // generate
    Random random = new Random();
    
    while(true){
      int randomValue = random.nextInt(10);
      if(randomValue == 0){
        break;
      }
      al.add(randomValue); // Store one by one until 0 appears
    }
 
    for (Integer n: al) {// Turn by a special for statement and display one by one
      System.out.print(n); // Output result example: 234245...
    }

As a method,

add() -> add element (used in above example)

size() -> get number of elements

remove() -> remove element with specified number

isEmpty() -> returns true if the list has no elements