How can I dynamically add items to a Java array?

kamikaze_pilot picture kamikaze_pilot · Feb 21, 2011 · Viewed 361.9k times · Source

In PHP, you can dynamically add elements to arrays by the following:

$x = new Array();
$x[] = 1;
$x[] = 2;

After this, $x would be an array like this: {1,2}.

Is there a way to do something similar in Java?

Answer

corsiKa picture corsiKa · Feb 21, 2011

Look at java.util.LinkedList or java.util.ArrayList

List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);