Dynamic Array List size
17,354
Solution 1
array size needs to be fixed while initialization, use List
instead and then have array from List
using toArray()
For example:
List<Integer> listOfInt = new ArrayList<Integer>(); //no fixed size mentioned
listOfInt .add(1);
listOfInt .add(2);
listOfInt .add(3);
//now convert it to array
Integer[] arrayOfInt = list.toArray(new Integer[listOfInt .size()]);
Solution 2
Your title is confusing. Are you using an ArrayList or an Array.
An ArrayList
expands and shrinks as needed each time you call the add
, remove
method respectively (or any other add/remove variant). There is no need to manage its size yourself.
A list is initialized as follows:
List<Integer> lst = new ArrayList<Integer>();
Now you have a list where you can add a virtual infinite amount of elements.
An array
needs its size on initialization which cannot be changed without reinitializing.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 05, 2022Comments
-
Admin about 2 years
How can I set size of a dynamic array with Java?
I tried
setsize(...)
with the array variable but not working. How can I do this? -
Tudor about 12 yearsMaybe suggest
ArrayList
in particular, since it actually uses an array under the hood? -
Andres F. about 12 years+1 Almost surely the OP is trying to ask about
ArrayList
, but it's confusing. -
jmj about 12 yearsYes you could use
ArrayList
implementation as @Tudor mentioned in comment -
Admin about 12 yearsList<Integer>[911] A = new ArrayList<Integer>(); but says it is not statement, im confused
-
jmj about 12 yearsAdded example, it would help more