Friday, May 31, 2013

What To Do If Size of Array Is Not Known Initially In Java?

What To Do If Size of Array Is Not Known Initially In Java?
(or)
How to dynamically allocate array in Java ?

To dynamically allocate array in Java, use the copyOf () method of Arrays class. Let us consider an example Java program to read numbers from the user until -1 is pressed. So initially, the size of array is not known. So let me create a 1 element array. For explanation, I am using int arrray.

int[] arr= new int[1];  ------> Initially, the array size is set to 1
System.out.println("Enter the items and press -1 to Quit");
if(i>1){
       arr=Arrays.copyOf(arr,arr.length+1); ------->Use copyOf function of java.util.Arrays class
}
arr[i]=s.nextInt(); // s is the object of java.util.Scanner class

No comments:

Post a Comment