Adding integer to an array (Java)

Hey there,

This has always boggled my mind a bit too, since it’s so easy to do in other languages. But the best way to do this in Java would be to use an ArrayList or List. If you want to start out with the initial list, you have to import java.util.* to give you the Arrays.asList method.

import java.util.*;

ArrayList<Integer> numbers;

numbers = new ArrayList<Integer>(Arrays.asList(1, 2, 3));

println(numbers);

numbers.add(10);

//prints 1,2,3

println(numbers);

// prints 1,2,3,10
2 Likes