I am creating in array without knowing the number of elements and instead of asking number of elements from the use I want to keep on storing till the user stops giving more inputs. How to do that in java?
2 Answers
Java has data structures that already do this for you (e.g. ArrayList). But if you really need to implement it yourself, then a standard method would be to store the number of elements you've currently stored separately from the capacity of the array (i.e. its length).
For example for a String array that starts at size 10 and doubles in size when it is full:
String[] array = new String[10];
int size = 0;
private add(String item) {
if (size == array.length)
array = Arrays.copyOf(array, array.length * 2);
array[size++] = item;
}
If performance isn't important then you can expand on every element and avoid storing the size (as it's always equal to the array's length):
array = Arrays.copyOf(array, array.length + 1);
array[array.length - 1] = item;
ArrayListinstead of an array, or re-dimension your array (i.e. create a bigger array and copy all elements) when your array gets too small.ArrayListand don't look back.