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?
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?
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between
array
andarraylist
.The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Here is the simple picture of it
And finally here is the code:
Step 1:
Step 2:
Step 3:
Step 4
Use an ArrayList or juggle to arrays to auto increment the array size.
Look at java.util.LinkedList or java.util.ArrayList
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
keep a count of where you are in the primitive array
You can use an
ArrayList
and then use thetoArray()
method. But depending on what you are doing, you might not even need an array at all. Look into seeing ifLists
are more what you want.See: Java List Tutorial