Java Arrays copyOf 方法拷贝short类型


Java Arrays copyOf 方法拷贝short类型

package com.codingdict;

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {

      // intializing an array arr1
      short[] arr1 = new short[]{15, 10, 45};

      // printing the array
      System.out.println("Printing 1st array:");
      for (int i = 0; i < arr1.length; i++) {
         System.out.println(arr1[i]);
      }
      // copying array arr1 to arr2 with newlength as 5 as Object
      Object arr2 = Arrays.copyOf(arr1, 5);

      // cast arr2 as short in order to be printable
      short[] arr3 = (short[]) arr2;

      // printing the array arr2. Since arr3 is a short[],nulls are now 0
      System.out.println("Printing new array:");
      for (int i = 0; i < 5; i++) {
         System.out.println(arr3[i]);
      }
   }
}