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?

3
  • 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. Commented Sep 23, 2019 at 3:46
  • Take a look at this. stackoverflow.com/questions/1647260/java-dynamic-array-sizes Commented Sep 23, 2019 at 3: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. Commented Sep 23, 2019 at 4:03

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.