What are the methods of defining arrays in Java?

There are several ways to define an array in Java.

  1. Initialize an array using array literals.
int[] arr = {1, 2, 3, 4, 5};
  1. Create and initialize an array using the new keyword.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
  1. Initialize an array using the static methods of the Arrays class.
int[] arr = new int[5];
Arrays.fill(arr, 0); // 将数组元素初始化为0
  1. Initialize the array with a loop.
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
    arr[i] = i + 1;
}
  1. Create and initialize an array using the newInstance() method of the Array class.
int[] arr = (int[]) Array.newInstance(int.class, 5);
for (int i = 0; i < arr.length; i++) {
    arr[i] = i + 1;
}

These are common methods for defining arrays, each method is suitable for different scenarios, developers can choose the appropriate method based on specific requirements.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds