Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java array


May 10, 2021 Java


Table of contents


Java array

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

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

You can declare an array variable, such as numbers100, 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 them the corresponding code.


Declare array variables

Array variables must be declared before they can be used in a program. Here is the syntax for declaring array variables:

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

或

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

Note: It is recommended to declare array variables using the declaration style of dataType s arrayRefVar. The dataType arrayRefVar style comes from the C/C language and is used in Java to enable C/C?programmers to quickly understand the java language.

Instance

Here's an example of code for both syntaxes:

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

Create an array

The Java language uses the new operator to create arrays with the following syntax:

arrayRefVar = new dataType[arraySize];

The syntax statement above does two things:

  • I. Create an array using dataType (arraySize).

  • Second, assign a reference to the newly created array to the variable arrayRefVar.

The declaration of array variables, and the creation of arrays, can be done in one statement, as follows:

dataType[] arrayRefVar = new dataType[arraySize];

In addition, you can create arrays in the following ways.

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

The elements of the array are accessed through an index. The array index starts at 0, so the index values start at 0 to arrayRefVar.length-1.

Then when the array opens up space, you can do it as follows:

  • Access to the array is done through the index, i.e.: "Array name ( index) " , but it is important to note that the index of the array starts at 0, so the index range is 0 to array length-1, for example, an array that opens up 3 spaces, so the index that can be used is: 0,1,2, if the index range of the array is exceeded at this time, the java.lang.ArrayIndexOutBoundsException exception information is generated;
  • When our array opens up space with dynamic initialization, each element in the array is the default value for the data type of the array;
  • The array itself is an ordered collection operation, so the content operation of the array is often done in a circular pattern, and the array is a limited collection of data, so you should use the for loop.
  • In Java, there is a way to dynamically get the length of an array: array name.length;

Example: Define an int array

public class ArrayDemo {
	public static void main(String args[]) {
		int data[] = new int[3]; /*开辟了一个长度为3的数组*/
		data[0] = 10; // 第一个元素
		data[1] = 20; // 第二个元素
		data[2] = 30; // 第三个元素
		for(int x = 0; x < data.length; x++) {
			System.out.println(data[x]); //通过循环控制索引
		}
	}
}

The array itself has another open pattern in addition to declaring and opening up space.

Example: Open up array space in step-by-step mode

public class ArrayDemo {
	public static void main(String args[]) {
		int data[] = null; 
		data = new int[3]; /*开辟了一个长度为3的数组*/
		data[0] = 10; // 第一个元素
		data[1] = 20; // 第二个元素
		data[2] = 30; // 第三个元素
		for(int x = 0; x < data.length; x++) {
			System.out.println(data[x]); //通过循环控制索引
		}
	}
}

However, it is important to remember that arrays belong to reference data types, so be sure to open controls (instantiation) before using them, and if you use arrays that do not open controls, you will have NullPointerException exception information:

public class ArrayDemo {
	public static void main(String args[]) {
		int data[] = null; 
		System.out.println(data[x]);
	}
}

This principle is exactly the same as what was explained earlier.

Arrays are bound to be used in development, but operations like the one above are rare. In later actual development, the array concept will be used more, and direct use, 99% of cases are just a for loop output.


Process the array

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

Example

This example provides a complete picture of how to create, initialize, and manipulate arrays:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.92.93.43.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 above examples compile and run 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 type of loop, called a foreach loop or an enhanced loop, that can traverse arrays without using the underseed.

The syntax format is as follows:

for(type element: array)
{
    System.out.println(element);
}

Example

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

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.92.93.43.5};

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

The above examples compile and run as follows:

1.9
2.9
3.4
3.5

The array is used as an argument to the function

Arrays can be passed to methods as arguments. For example, the following example is a way to print 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[]{312642});

The return value of the array as a 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 the return value of the function.


Array class

The java.util.Arrays class can easily manipulate arrays, and all the methods it provides are static. It has the following features:

  • Assign a value to an array: by the fill method.

  • Sort arrays: Ascending by the sort method.

  • Compare arrays: Compare whether element values in an array are equal by the equals method.

  • Find array elements: The binarySearch method provides a two-way lookup of sorted arrays.

See the table below for specific instructions:

Serial number Methods and instructions
1 public static int binarySearch(Object[] a, Object key)
Search for objects of a given value (Byte, Int, double, etc.) in a given array using a two-point lookup algorithm. A rrays must be sorted before they can be called. If the lookup value is included in the array, the index of the search key is returned;
2 public static boolean equals(long[] a, long[] a2)
True is returned if the two specified long arrays are equal to each other. I f two arrays contain the same number of elements, and all corresponding pairs of elements in both arrays are equal, the two arrays are considered equal. I n other words, if two arrays contain the same elements in the same order, the two arrays are equal. The same approach applies to all other basic data types (Byte, short, Int, etc.).
3 public static void fill(int[] a, int val)
Assign the specified int value to each element in the specified range of the specified int array. The same approach applies to all other basic data types (Byte, short, Int, etc.).
4 public static void sort(Object[] a)
Arrays of specified objects are ascending according to the natural order of their elements. The same approach applies to all other basic data types (Byte, short, Int, etc.).