ArrayList class

A normal array is used 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 the 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 with a special for statement and display one by one
      System.out.print(n); //Output result example: 234245...
    }

As a method, mainly

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

size ()-> Get number of elements

remove ()-> remove the element with the specified number

isEmpty ()-> returns true when there are no elements in the list

Recommended Posts

ArrayList class
ArrayList
[Practice] ArrayList
11th class: Class
Anonymous class (anonymous class)
Class method
ObjectMapper class
ArrayList practice
JDBC class load
Java class methods
Class and model
[Java] Class inheritance
9th class: assert_equal
java Scanner class
Decompile class files
LinkedList and ArrayList
java (abstract class)
Class in Ruby
[Java] Nested class
Java anonymous class
About Java class
8th class: rake
String class methods
[Week 11] class, ruby_sixth
java.lang.IncompatibleClassChangeError: Implementing class
[java] abstract class
Java local class
5th class: Output
Impl class Vo class
WildFly class loading
Extract elements in order from a class type ArrayList
[Java] Object operation of ArrayList class (AOJ ④ Inversion of sequence)
A memo that handles a class created independently with ArrayList