To add integers to an ArrayList
in Java, you can use the add
method of the ArrayList
class.
Here's an example of how you could use the add
method to add integers to an ArrayList
:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); System.out.println(list); } }Source:wal.wwutturi.com
In this example, the ArrayList
object named list
is initialized with no elements. The add
method is then used to add three integers to the list
. Finally, the list
is printed using the println
method.
The output of this example would be the following ArrayList
:
[1, 2, 3]
Keep in mind that the ArrayList
class is part of the java.util
package, which is included in the standard Java SE library. You can use a similar approach to add other types of objects to an ArrayList
, by replacing the generic type Integer
with the appropriate type. For example, to add String
objects to an ArrayList
, you can use the ArrayList<String>
type.
You can also add multiple elements to an ArrayList
at once using the addAll
method, or using an array or a collection as an argument. Here's an example of how you could use the addAll
method to add multiple elements to an ArrayList
:
import java.util.ArrayList; import java.util.Arrays; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.addAll(Arrays.asList(1, 2, 3)); System.out.println(list); } }
In this example, the ArrayList
object named list
is initialized with no elements. The addAll
method is then used to add three integers to the list
, using the Arrays.asList
method to create a list from an array. Finally, the list
is printed using the println
method.
The output of this example would be the same as the previous example:
[1, 2, 3]
Keep in mind that the addAll
method adds the elements to the end of the ArrayList
.