EN
Java - create List with values initialized on creation
0 points
In this article, we would like to show you how to create List with values initialized on creation in Java.
Quick solution:
xxxxxxxxxx
1
List<Integer> numbers = Arrays.asList(1, 2, 3);
2
System.out.println(numbers); // [1, 2, 3]
In this example, we use Arrays.asList()
method to add items to the list on its creation.
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.util.List;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
List<Integer> numbers = Arrays.asList(1, 2, 3);
8
System.out.println("Numbers: " + numbers); // [1, 2, 3]
9
10
List<String> letters = Arrays.asList("A", "B", "C");
11
System.out.println("Letters: " + letters); // [A, B, C]
12
}
13
}
Output:
xxxxxxxxxx
1
Numbers: [1, 2, 3]
2
Letters: [A, B, C]