Java Creating an ArrayList

Java Creating an ArrayList

An ArrayList is a resizable array implementation of the List interface in Java. It allows you to store a collection of elements in an ordered sequence and provides various methods for inserting, deleting, and accessing elements in the list.

Here is an example of how to create an ArrayList in Java:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayList
    ArrayList<String> list = new ArrayList<>();

    // Add elements to the ArrayList
    list.add("Apple");
    list.add("Banana");
    list.add("Cherry");
    list.add("Date");
    list.add("Elderberry");

    // Print the ArrayList
    System.out.println(list);  // Output: [Apple, Banana, Cherry, Date, Elderberry]
  }
}
Source:‮.www‬lautturi.com

In this example, we create an ArrayList of type String and add some elements to it. The ArrayList stores the elements in the order in which they were added.

You can also create an ArrayList with an initial capacity, which specifies the number of elements the ArrayList can hold before it needs to resize itself. Here is an example:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayList with an initial capacity of 10
    ArrayList<String> list = new ArrayList<>(10);

    // Add elements to the ArrayList
    list.add("Apple");
    list.add("Banana");
    list.add("Cherry");
    list.add("Date");
    list.add("Elderberry");

    // Print the ArrayList
    System.out.println(list);  // Output: [Apple, Banana, Cherry, Date, Elderberry]
  }
}

In this example, we create an ArrayList with an initial capacity of 10. The ArrayList will allocate an array with a size of 10 to store the elements, which can help improve performance if you know that the ArrayList will contain a large number of elements.

Created Time:2017-11-03 00:14:40  Author:lautturi