If I need to use an array that I don’t know the size and it’s value,how could I declare or initial it in Java program? I have try ArrayList ,it works,but how to did it with an array?

3 Answers

2
Robby Cornelissen On Best Solutions

The values of an array can be changed at any point, but the size is fixed upon array creation.

If the size is unknown when you create the array, your options are:

  • Create an array that is sure to be big enough to fit all your use cases. This has memory implications as you might me allocating far more memory than you actually require.
  • Create an array that is relatively small; when you exceed its bounds, create a bigger array and copy the contents of the old array to the new array. This has performance implications, as copying the elements requires processing.

The second approach is the approach taken by the ArrayList class, which takes care of this for you.

0
Adwaith R Krishna On

Arrays in Java are of fixed size. Dynamic sizes which can be achieved by

arr=new int[N] // value of N is obtained at run time.

here the value of N is obtained during run time.

Otherwise you can write a function which will expand the arrays (when the array is filled) using

  • java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.

  • using java.lang.System.arraycopy(...), which will create a new array of the desired size, and copy the contents from the original array to the new array.

It's Better to use one of Java's data structures such as Vector or ArrayList (ArrayLists which is a collection & can dynamically scale).

0
Community On

Ask from the reviewer to type in an integer which is going to represent the positions of the array. You can also verify that the number which is going to be typed in is going to be in a specific range of your own choosing. Then create the array. The code in java is like this

import java.util.*; import java.lang.*;

public static void main (String args[]){

Scanner sc=new Scanner(System.in);

System.out.println("Type in the number of the positions of the array");
int N=sc.nextInt();

// verify the the N is in a specific range of your own choosing'

for(;;)
{
   if ( (N>0)&&(N<10000)) break;
}
int[] A=new int[N];

// handle the array as you wish 

}