To create a list of numbers from 1 to n in Java, you can use a loop to iterate over the range of numbers and add each number to the list. Here is an example of how to do this using the ArrayList
class:
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { int n = 10; List<Integer> list = new ArrayList<>(); for (int i = 1; i <= n; i++) { list.add(i); } System.out.println(list); // Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } }
In this example, a loop is used to iterate over the range of numbers from 1 to n. The add
method of the ArrayList
object is called in each iteration to add the current number to the list.
You can also use the List.of
method to create a list of numbers in a more concise way:
import java.util.List; public class Main { public static void main(String[] args) { int n = 10; List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); System.out.println(list); // Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } }
In this example, the List.of
method is used to create a list of numbers from 1 to 10. The List.of
method returns an immutable list, which means that the list cannot be modified after it is created.
You can use a loop or the List.of
method to create a list of numbers from 1 to n in Java. The ArrayList
class allows you to create a mutable list, while the List.of
method returns an immutable list.