New arraylist
Here is an example of how to create a new ArrayList
in Java:
import java.util.ArrayList;
// Create a new ArrayList
ArrayList<String> myList = new ArrayList<>();
In this example, we are creating a new ArrayList
called myList
that can hold String
objects.
You can also specify the initial capacity of the ArrayList
when creating it:
import java.util.ArrayList;
// Create a new ArrayList with an initial capacity of 10
ArrayList<String> myList = new ArrayList<>(10);
This can be useful if you know in advance how many elements you will be adding to the ArrayList
.
Alternatively, you can use the ArrayList
constructor that takes a Collection
as an argument:
import java.util.ArrayList;
import java.util.Collections;
// Create a new ArrayList from an existing Collection
ArrayList<String> myList = new ArrayList<>(Collections.emptyList());
This can be useful if you already have a Collection
that you want to convert to an ArrayList
.
Note that ArrayList
is a resizable array, which means that it can grow or shrink dynamically as elements are added or removed.