Java Program to extend the size of an Integer array

Java 8Object Oriented ProgrammingProgramming

Let us first create an Integer array −

Integer[] arr = new Integer[] { 50, 100, 150, 200, 400, 500, 800, 1000};

Now, create a new array with the extended size −

Integer[] new_size = new Integer[15];

Add elements for the extended size −

new_size[8] = 2000;
new_size[9] = 3000;
new_size[10] = 4000;
new_size[11] = 5000;
new_size[12] = 6000;
new_size[13] = 9000;
new_size[14] = 10000;

Now, copy the array and form it the final array with the extended size −

System.arraycopy(arr, 0, new_size, 0, arr.length);

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      Integer[] arr = new Integer[] { 50, 100, 150, 200, 400, 500, 800, 1000};
      System.out.println("All the elements before extending the array...");
      for (Integer i:arr)
      System.out.println(i);
      Integer[] new_size = new Integer[15];
      new_size[8] = 2000;
      new_size[9] = 3000;
      new_size[10] = 4000;
      new_size[11] = 5000;
      new_size[12] = 6000;
      new_size[13] = 9000;
      new_size[14] = 10000;
      System.arraycopy(arr, 0, new_size, 0, arr.length);
      System.out.println("All the elements after extending the array...");
      for (Integer i: new_size)
      System.out.println(i);
   }
}

Output

All the elements before extending the array...
50
100
150
200
400
500
800
1000
All the elements after extending the array...
50
100
150
200
400
500
800
1000
2000
3000
4000
5000
6000
9000
10000
raja
Published on 23-Apr-2019 16:19:55
Advertisements