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
By using copyOf method in java.util.Arrays
class String[]
size will increment automatically / dynamically. In below code array
size 0
after manipulation of using Arrays.copyOf
the size of String array
is increased to 4
.
package com.google.service;
import java.util.Arrays;
public class StringArrayAutoIncrement {
public static void main(String[] args) {
String[] data = new String[] { "a", "b", "c", "d", "e" };
String[] array = new String[0];// array initialize with zero
int incrementLength = 1;
for (int i = 0; i < data.length; i++) {
array = Arrays.copyOf(data, i + incrementLength);// increment by +1
}
/**
* values of array after increment
*/
for (String value : array) {
System.out.println(value);
}
}
}
Output:
a
b
c
d
e