To add a pair of numbers to an ArrayList
in Java, you can use the add
method of the ArrayList
class to add the numbers as elements to the list.
Here is an example of how to add a pair of numbers to an ArrayList
in Java:
List<Integer> list = new ArrayList<>(); int a = 10; int b = 20; list.add(a); list.add(b); System.out.println(list);
In this example, the list
variable is defined as an ArrayList
of integers, and the ArrayList
class is used to instantiate the list. The a
and b
variables are defined as integers and initialized with the values 10
and 20
, respectively. The add
method is used to add the a
and b
variables to the list, and the System.out.println
method is used to print the list to the console.
You can use this approach to add a pair of numbers to an ArrayList
in Java by defining an ArrayList
and using the add
method to add the numbers as elements to the list. You can also customize this approach by using different types of numbers, such as integers, floats, or doubles, or by using different methods to add the numbers to the list.
Note that you can also use the addAll
method of the ArrayList
class to add multiple elements to the list at once, or the Collections.addAll
method to add an array of elements to the list.
List<Integer> list = new ArrayList<>(); int[] numbers = {10, 20}; list.addAll(Arrays.asList(numbers)); System.out.println(list);
In this example, the numbers
array is defined as an array of integers and initialized with the values 10
and 20
, and the addAll
method is used to add the elements of the array to the list. The Arrays.asList
method is used to convert the array to a list, and the System.out.println
method is used to print the list to the console.