How To Reduce The Size Of An Array In Java

In this section, we will see how to reduce the size of an array In Java. Can you change the size of an array in Java? No, we can’t reduce the size of an array in Java. In Java, arrays are fixed in size which means once an array is created then we can’t modify its size. But if there is a need to change the size of an array in Java then we can create another array of the required length and copy the required elements to the new array. In this way, we can reduce the size of an array.

For example:-
array = [1, 2, 3]
The above array is of size 3, we want to reduce it to 2.
array1 = resize(array, 2)
array1 = [1, 2]

How to Resize Array Java

import java.util.Arrays;

public class Main {
   public static void main(String[] args) {
      int[] array = { 1, 2, 3, 4, 5 };
      System.out.println("Array elements are: " 
                         + Arrays.toString(array));
      array = (int[]) resize(array, 3);

      System.out.println("The new array elements are: " 
                         + Arrays.toString(array));
   }

   private static Object resize(Object oldArray, int newSize) {
      int oldSize = java.lang.reflect.Array.getLength(oldArray);
      Class<?> elementType = oldArray.getClass().getComponentType();
      Object newArray = 
           java.lang.reflect.Array.newInstance(elementType, newSize);
      int preserveLength = Math.min(oldSize, newSize);
      if (preserveLength > 0) {
         System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
      }
      return newArray;
   }
}

Output:-

Array elements are: [1, 2, 3, 4, 5]
The new array elements are: [1, 2, 3]

Using the above resize() method we can reduce the length of any type of array in Java. In the above program, we have used reflection API and System.arraycopy() method. In Java, the System class contains lots of native methods like arraycopy() method. The arraycopy() is a native method and it uses a direct memory copy outside of Java land.

Java Resize Array

Let us see another program to reduce the size of an array in Java using Arrays.copyOf() method. The copyOf() method of Java Arrays class internally uses System.arraycopy() method itself.

import java.util.Arrays;

public class Main {
   public static void main(String[] args) {
      int[] array = { 12, 24, 63, 45, 50 };
      System.out.println("Array before Resize: " 
                         + Arrays.toString(array));

      array = Arrays.copyOf(array, 3);
      System.out.println("Array after Resize: " 
                        + Arrays.toString(array));
   }
}

Output:-

Array before Resize: [12, 24, 63, 45, 50]
Array after Resize: [12, 24, 63]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.