1

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?

Menlam Choden
  • 49
  • 3
  • 9
  • 5
    Either use an `ArrayList` instead of an array, or re-dimension your array (i.e. create a bigger array and copy all elements) when your array gets too small. – Robby Cornelissen Sep 23 '19 at 03:46
  • Take a look at this. https://stackoverflow.com/questions/1647260/java-dynamic-array-sizes – FailingCoder Sep 23 '19 at 03:50
  • A dynamic array is a fun thing to try sometime if you're intellectually curious and have some free time to waste. Otherwise, yeah, just go the an `ArrayList` and don't look back. – Kevin Anderson Sep 23 '19 at 04:03

2 Answers2

2

You can use ArrayList or HashSet (if uniqueness is required). Collections can grow dynamically as required. If you need array as a type, accept user data into Arraylist (or any other collection) and then create array from collection using toArray

Amit Patil
  • 710
  • 9
  • 14
0

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;
sprinter
  • 27,148
  • 6
  • 47
  • 78