Yes you can increase the size of an array by calling Arrays.copyOf
method and then reassigning it to initial object. But anyhow if you don't want to go through copying again and again ArrayList
is a better choice since it internally uses Arrays.copyOf
to increase the size of Array as it internally does it when you call add(E e) as:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
ensureCapacityInternal(size + 1)
checks for the max of Default capacity allocated i.e. 10 to size+1 as:
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
If the capacity exceeds ensureExplicitCapacity(minCapacity);
is called which increases the capacity of transient Object[]
by calling grow()
which internally does Arrays.copyOf
.
Hope this explanation helps.
For your problem you can perform it as:
String array[][] = { { "hello", "how" }, { "are", "you" } };
Scanner scan = null;
String str = null;
int len = array.length;
int i = 0;
while (i != 6) { // provide the loop as you require
scan = new Scanner(new InputStreamReader(System.in));
str = scan.next();
try {
array[len][1] = str; // will try to add to second position. If array is out of index an exception will be thrown
len++; // won't increase if exception is thrown
} catch (ArrayIndexOutOfBoundsException e) {
array = Arrays.copyOf(array, len + 1); // copying the array
array[len] = new String[2]; // creating and assigning string array to new row else it will be null
array[len][0] = str; // adding new string to new array position
}
i++;
}
scan.close();
for (String[] strings : array) {
for (String string : strings) {
System.out.println(string);
}
}