In Java, you can declare and insert values into an ArrayList
in the same line using the add
method and the Arrays.asList
method.
For example, consider the following code that declares an ArrayList
of strings and inserts three values into it:
import java.util.ArrayList; import java.util.Arrays; ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
The Arrays.asList
method returns a fixed-size list backed by the specified array. The add
method adds the elements of the list returned by Arrays.asList
to the ArrayList
.
You can also use this syntax to declare an ArrayList
and insert values into it in a single line of code:
ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "cherry"));
This creates an ArrayList
with the elements "apple", "banana", and "cherry".
Note that this syntax is only suitable for inserting a small number of values into the ArrayList
. If you need to insert a large number of values, it is more efficient to use the add
method in a loop.
For example:
ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < 100; i++) { list.add("Value " + i); }
This will insert 100 values into the ArrayList
.