To add elements to an array dynamically in Java, you can use a collection class, such as ArrayList
, or create a new array and copy the elements manually.
Here's an example of how you could use an ArrayList
to add elements to an array dynamically:
import java.util.ArrayList; import java.util.Arrays; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); int[] numbers = list.stream().mapToInt(i -> i).toArray(); System.out.println(Arrays.toString(numbers)); } }Source:l.wwwautturi.com
In this example, the ArrayList
object named list
is initialized with three elements using the add
method. Then, the stream
method is used to create a stream of the elements in the list
, and the mapToInt
and toArray
methods are used to convert the stream to an int
array. Finally, the Arrays.toString
method is used to print the numbers
array as a string.
The output of this example would be the following array:
[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 elements to an array dynamically using other collection classes, such as LinkedList
, Vector
, or Queue
.