4

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?

2 Answers 2

15

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()]);
Sign up to request clarification or add additional context in comments.

4 Comments

Maybe suggest ArrayList in particular, since it actually uses an array under the hood?
Yes you could use ArrayList implementation as @Tudor mentioned in comment
List<Integer>[911] A = new ArrayList<Integer>(); but says it is not statement, im confused
Added example, it would help more
1

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.

1 Comment

+1 Almost surely the OP is trying to ask about ArrayList, but it's confusing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.