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.

Share:
17,354
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    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
    Tudor about 12 years
    Maybe suggest ArrayList in particular, since it actually uses an array under the hood?
  • Andres F.
    Andres F. about 12 years
    +1 Almost surely the OP is trying to ask about ArrayList, but it's confusing.
  • jmj
    jmj about 12 years
    Yes you could use ArrayList implementation as @Tudor mentioned in comment
  • Admin
    Admin about 12 years
    List<Integer>[911] A = new ArrayList<Integer>(); but says it is not statement, im confused
  • jmj
    jmj about 12 years
    Added example, it would help more