Java: ArrayList

The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified. While elements can be added and removed from an ArrayList whenever you want.

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  }
}

// Outputs
[Volvo, BMW, Ford, Mazda]

Sort an ArrayList

import java.util.ArrayList;
import java.util.Collections;  // Import the Collections class

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    Collections.sort(cars);  // Sort cars

    System.out.println(i);
  }
}

// Outputs
[BMW, Ford, Mazda, Volvo]

 

posted @ 2022-11-27 07:25  小白冲冲  阅读(22)  评论(0)    收藏  举报