Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase the size of an array in Java?

Tags:

java

arrays

size

I want to store as many elements as desired by the user in an array. But how do I do it.

If I were to create an array, I must do so with a fixed size. Every time a new element is added to the array and the array becomes full, I want to update its size by '1'.

I tired various types of code, but it did not work out.

It would be of great help if someone could give me a solution regarding it - in code if possible.

like image 401
joel abishai paul Avatar asked Sep 21 '12 04:09

joel abishai paul


People also ask

How do you make an array bigger?

resize() can create an array of larger size than the original array. To convert the original array into a bigger array, resize() will add more elements (than available in the original array) by copying the existing elements (repeated as many times as required) to fill the desired larger size.

How do you double the size of an array in Java?

intnewArray[] = new int[len*2]; Now, newArray[] will be having twice the length of the array arr[].

Can we resize an array?

You cannot resize an array in C#, but using Array. Resize you can replace the array with a new array of different size.


2 Answers

Instead of using an array, use an implementation of java.util.List such as ArrayList. An ArrayList has an array backend which holds values in a list, but the array size is automatically handles by the list.

ArrayList<String> list = new ArrayList<String>();
list.add("some string");

You can also convert the list into an array using list.toArray(new String[list.size()]) and so forth for other element types.

like image 86
FThompson Avatar answered Oct 18 '22 08:10

FThompson


On a low level you can do it this way:

long[] source = new long[1];
long[] copy = new long[source.length + 1];
System.arraycopy(source, 0, copy, 0, source.length);
source = copy;

Arrays.copyOf() is doing same thing.

like image 42
A Kunin Avatar answered Oct 18 '22 06:10

A Kunin