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?
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()]);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.