Reputation: 38
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?
Upvotes: 1
Views: 487
Reputation: 6969
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.
Upvotes: 5