1

So I'm confused why this isn't considered a dynamic array?

public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    int n = in.nextInt();
    int[] array = new int[n];
    for ( int i = 0; i < n; i++) {
        array[i] = i;
    }

    for ( int i = 0; i < n; i++) {
        System.out.print(array[i]);

Should I be using ArrayList instead here or is this usage ok?

3
  • In general arrays in Java are dynamically allocated, but have fixed size (unless you reallocate). Commented Jul 18, 2016 at 1:05
  • 4
    When you create an array, you specify (declare) the size of it at the start. With a list you do not have to do that. That is the main difference. If you later decide that you want more than n elements in your array, it is not possible, but with a list it would be (of course, a list doesn't do magic, but you get the point). Commented Jul 18, 2016 at 1:05
  • What makes you think it is a dynamic array? Commented Jul 18, 2016 at 1:39

1 Answer 1

5

Java doesn't have dynamic arrays. Once an array has been created it's size cannot be changed.

ArrayList uses an internal array for storage, but it resizes the array internally so you don't have to worry about it.

Internally of course it simply creates a new, larger array and copies things over when it needs more space.

As for if your usage of array is OK, for the given scenario, it is. If your array content size is unknown or if it can change, then switch to ArrayList rather than doing the resizing yourself.

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

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.