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.
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.
intnewArray[] = new int[len*2]; Now, newArray[] will be having twice the length of the array arr[].
You cannot resize an array in C#, but using Array. Resize you can replace the array with a new array of different size.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With