Java array


Arrays are one of the important data structures for every programming language. Of course, different languages ​​implement and process arrays differently.

Arrays provided in the Java language are used to store fixed-size elements of the same type.

You can declare an array variable, such as numbers[100] instead of directly declaring 100 independent variables number0, number1, ...., number99.

This tutorial will introduce you to the declaration, creation and initialization of Java arrays, and give you the corresponding code.


Declare array variables

First, you must declare an array variable before you can use the array in the program. The following is the syntax for declaring array variables:

dataType[] arrayRefVar;   // 首选的方法

或

dataType arrayRefVar[];  // 效果相同,但不是首选方法

Note: It is recommended to use the declaration style of dataType[] arrayRefVar to declare array variables. The dataType arrayRefVar[] style comes from the C/C++ language and is adopted in Java to allow C/C++ programmers to quickly understand the java language.

Examples

The following are code examples of these two syntaxes:

double[] myList;         // 首选的方法

或

double myList[];         //  效果相同,但不是首选方法

Creating arrays

The Java language uses the new operator to create arrays , the syntax is as follows:

arrayRefVar = new dataType[arraySize];

The above syntax statement does two things:

  • 1. Use dataType[arraySize] to create an array.

  • 2. Assign the reference of the newly created array to the variable arrayRefVar.

The declaration of array variables and the creation of an array can be completed in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

In addition, you can also create an array in the following way.

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The elements of the array are accessed by index. Array indexing starts at 0, so index values ​​range from 0 to arrayRefVar.length-1.

Example

The following statement first declares an array variable myList, then creates an array containing 10 double type elements, and assigns its reference to the myList variable.

public class TestArray {

   public static void main(String[] args) {
      // 数组大小
      int size = 10;
      // 定义数组
      double[] myList = new double[size];
      myList[0] = 5.6;
      myList[1] = 4.5;
      myList[2] = 3.3;
      myList[3] = 13.2;
      myList[4] = 4.0;
      myList[5] = 34.33;
      myList[6] = 34.0;
      myList[7] = 45.45;
      myList[8] = 99.993;
      myList[9] = 11123;
      // 计算所有元素的总和
      double total = 0;
      for (int i = 0; i < size; i++) {
         total += myList[i];
      }
      System.out.println("总和为: " + total);
   }
}

The output result of the above example is:

总和为: 11367.373

The following picture depicts the array myList. Here, there are 10 double elements in the myList array, and their subscripts range from 0 to 9.

12-130Q0221Q5602.jpg


Processing arrays

The element type of the array and the size of the array are determined, so when processing array elements, we usually use the basic Loop or foreach loop.

Example

This example completely demonstrates how to create, initialize and manipulate an array:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // 打印所有数组元素
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // 计算所有元素的总和
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // 查找最大元素
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

The compilation and running results of the above example are as follows:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

foreach loop

JDK 1.5 introduces a new loop type, called foreach loop or enhanced loop, which can traverse an array without using subscripts.

Example

This example is used to display all elements in the array myList:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // 打印所有数组元素
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

The compilation and running results of the above example are as follows:

1.9
2.9
3.4
3.5

Array As arguments to functions

Arrays can be passed as arguments to methods. For example, the following example is a method that prints the elements in an int array.

public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}

The following example calls the printArray method to print out 3, 1, 2, 6, 4 and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

The array is used as the return value of the function

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    result[j] = list[i];
  }
  return result;
}

In the above example, the result array is used as the return value of the function.


Arrays class

The java.util.Arrays class can conveniently operate arrays, and all the methods it provides are static. Has the following functions:

  • Assign a value to the array: through the fill method.

  • Sort the array: use the sort method, in ascending order.

  • Compare arrays: Compare whether the element values ​​in the array are equal through the equals method.

  • Search for array elements: The binarySearch method can be used to perform a binary search operation on the sorted array.

Please see the table below for specific instructions:

              Serial number             Methods and instructions
            1public static int binarySearch(Object[] a, Object key)
Use the binary search algorithm to search for an object (Byte, Int, double, etc.) with a given value in a given array. The array must be sorted before calling. If the search value is contained in the array, returns the index of the search key; otherwise returns (-(INSERTION POINT) - 1).
              2public static boolean equals(long[] a, long[] a2)
Returns true if the two specified long arrays are equal to each other. Two arrays are considered equal if they contain the same number of elements and all corresponding pairs of elements in both arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. The same approach works for all other basic data types (Byte, short, Int, etc.).
              3public static void fill(int[] a, int val)
Assigns the specified int value to each element in the specified range of the specified int array. The same approach works for all other basic data types (Byte, short, Int, etc.).
              4public static void sort(Object[] a)
Sorts the specified array of objects in ascending order according to the natural ordering of its elements. The same approach works for all other basic data types (Byte, short, Int, etc.).