Java array explanation

Java array explanation

Definition of array

  • An array is an ordered collection of the same data type.
  • Array describes several data of the same type, which are arranged and combined in a certain order.
  • Among them, each data is called an array element, and each array element can access them through subscript.

Declaration and creation of arrays

Array variables must be declared before arrays can be used in programs. Here are two syntax for declaring array variables:

dataType[] arrayRefVar;		// Preferred method, recommended
 or
dataType arrayRefVar[];		// Reserved for C/C + + programmers, not recommended

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

arrayRefVar = new dataType[arraySize];

Example:

package com.wmwx.array;

public class Demo01 {
    public static void main(String[] args) {
        int[] numbers;          //Array declaration
        numbers = new int[5];   //Array creation
    }
}

Assignment of array

Arrays can be assigned by using subscripts. The subscript of the array starts from 0 and ends with length-1 (length is the length of the array).

If the subscript exceeds length-1, an error will be reported: arraylndexofboundsexception, that is, the array subscript is out of bounds.

Example:

package com.wmwx.array;

public class Demo01 {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        numbers[0] = 1;                     //Subscript starts at 0
        numbers[1] = 2;
        numbers[2] = 3;
        numbers[3] = 4;
        numbers[4] = 5;
        System.out.println(numbers[0]);     //Output 1
        System.out.println(numbers[1]);     //Output 2
        System.out.println(numbers[2]);     //Output 3
        System.out.println(numbers[3]);     //Output 4
        System.out.println(numbers[4]);     //Output 5
        System.out.println(numbers[5]);     //Error reporting: out of bounds exception
    }
}

Traversal of array

The element type of the array and the size of the array are determined. So when dealing with array elements, we usually use circular structure.

Example:

package com.wmwx.array;

public class Demo01 {
    public static void main(String[] args) {
        int[] numbers = new int[5];         //Declaration and creation
        numbers[0] = 1;                     //assignment
        numbers[1] = 2;
        numbers[2] = 3;
        numbers[3] = 4;
        numbers[4] = 5;
        int sum =  0;
        //Through array Length can get the length of the array
        for (int i = 0; i < numbers.length; i++) {
            sum = sum + numbers[i];
        }
        System.out.println(sum);            //Output 15
    }
}

Initialization of array

There are three ways to initialize an array:

  1. initiate static
  2. dynamic initialization
  3. Default initialization

Example:

package com.wmwx.array;

public class Demo02 {
    public static void main(String[] args) {
        //Static initialization: create + assign
        int[] a = {1, 2, 3, 4};
        System.out.println(a[0]);   //Output 1

        //Dynamic initialization (including default initialization)
        int[] b = new int[4];
        b[0] = 5;
        System.out.println(b[0]);   //Output 5

        //Default initialization
        System.out.println(b[1]);   //Output 0
        System.out.println(b[2]);   //Output 0
        System.out.println(b[3]);   //Output 0
    }
}

Basic characteristics of array

  1. Its length is determined. Once an array is created, its size cannot be changed. Its elements must be of the same type, and mixed types are not allowed.
  2. The elements in the array can be any data type, including basic type and reference type.
  3. Array variables belong to the reference type, and arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object.
  4. The array itself is an object, while the object in Java is in the heap. Therefore, whether the array holds the original type or other object types, the array object itself is in the heap.

For each loop

Java 5 introduces a new type of loop, called for each loop or enhanced loop, which can traverse arrays without subscripts.

Its syntax format is as follows:

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

Example:

package com.wmwx.array;

public class Demo03 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};

        //Output all elements of the array
        //for loop
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }

        //For each loop
        for (int i: array) {
            System.out.println(i);
        }
    }
}

Array as parameter and return value

Example:

package com.wmwx.array;

public class Demo04 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        int[] new_array = reverse(array);
        for (int i: new_array) {
            System.out.println(i);      //Output 5, 4, 3, 2, 1
        }
    }

    //Array as return value
    public static int[] reverse(int[] array){		//Array as parameter
        int[] result = new int[array.length];
        //Invert the entire array
        for (int i=0, j=array.length-1;i<array.length;i++,j--){
            result[j] = array[i];
        }
        return result;
    }
}

Multidimensional array

Multidimensional arrays can be regarded as arrays. For example, a two-dimensional array is a special one-dimensional array, and each element is a one-dimensional array.

Example:

package com.wmwx.array;

public class Demo05 {
    public static void main(String[] args) {
        //Two dimensional array
        int[][] array = {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}};

        System.out.println(array[0][1]);    //Output 2
        System.out.println(array[1][2]);    //Output 4
        System.out.println(array[2][0]);    //Output 3

        //Traversing a two-dimensional array
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.println(array[i][j]);
            }
        }
    }
}

Arrays class

java. util. The arrays class can easily manipulate arrays, and all the methods it provides are static.

It has the following functions:

  • Print array: through toString method
  • Assign a value to the array: through the fill method.
  • Sort the array: sort in ascending order through the sort method.
  • Compare arrays: use the equals method to compare whether the element values in the array are equal.
  • Find array elements: binary search can be performed on the sorted array through binarySearch method.

Example:

package com.wmwx.array;

import java.util.Arrays;

public class Demo06 {
    public static void main(String[] args) {
        int[] array = {1, 234, 56, 7890};

        //Print array
        System.out.println(array);                      //Output[ I@e73f9ac
        System.out.println(Arrays.toString(array));     //Output [1, 234, 56, 7890]

        //Sort array
        Arrays.sort(array);                             //Ascending sort
        System.out.println(Arrays.toString(array));     //Output [1, 56, 234, 7890]

        //Find element
        System.out.println(Arrays.binarySearch(array, 234));            //Output 2

        //Fill array
        Arrays.fill(array, 0);
        System.out.println(Arrays.toString(array));     //Output [0, 0, 0, 0]

        //Compare array
        System.out.println(Arrays.equals(array, new int[]{0, 0, 0, 0}));    //Output true
    }
}

Sparse array

When most elements in an array are 0 or the same value, you can use a sparse array to save the array.

Sparse arrays are handled as follows:

  • How many rows and columns are there in the record array? How many different values are there
  • Record the rows, columns and values of elements with different values in a small-scale array, so as to reduce the size of the program

Example:

package com.wmwx.array;

import java.util.Arrays;

public class Demo07 {
    public static void main(String[] args) {
        //On the chessboard of 11 * 11: 0 spaces, 1 black chess, 2 white chess
        int[][] chess = new int[11][11];
        chess[1][2] = 1;
        chess[2][3] = 2;
        //Output original array:
        System.out.println("The original array is as follows:");
        for (int[] arrs: chess) {
            for (int i: arrs) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
        System.out.println("=====================");
        //Convert to sparse array and output
        chess = sparse(chess);
        System.out.println("The sparse array is as follows:");
        for (int[] arrs: chess) {
            for (int i: arrs) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
        System.out.println("=====================");
        //Restore to original array and output
        chess = toArray(chess);
        System.out.println("Restore the array as follows:");
        for (int[] arrs: chess) {
            for (int i: arrs) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }

    public static int[][] sparse(int[][] array){
        //Step 1: get the number of valid values
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j]!=0){
                    sum++;
                }
            }
        }
        System.out.println("Number of valid values:"+sum);
        System.out.println("=====================");

        //Step 2: create a sparse array
        int[][] sparseArray = new int[sum+1][3];
        sparseArray[0][0] = array.length;
        sparseArray[0][1] = array[0].length;
        sparseArray[0][2] = sum;

        //Step 3: traverse the original array and store non-zero values in the sparse array
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j]!=0){
                    count++;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = array[i][j];
                }
            }
        }

        //Step 4: return sparse array
        return sparseArray;
    }

    public static int[][] toArray(int[][] sparse){
        //Step 1: build the original array
        int[][] array = new int[sparse[0][0]][sparse[0][1]];

        //Step 2: restore the value
        for (int i = 1; i < sparse.length; i++) {
            array[sparse[i][0]][sparse[i][1]] = sparse[i][2];
        }

        //Step 3: return the original array
        return array;
    }
}

The final output results are as follows:

The original array is as follows:
0 0 0 0 0 0 0 0 0 0 0 
0 0 1 0 0 0 0 0 0 0 0 
0 0 0 2 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
=====================
Number of valid values: 2
=====================
The sparse array is as follows:
11 11 2 
1 2 1 
2 3 2 
=====================
Restore the array as follows:
0 0 0 0 0 0 0 0 0 0 0 
0 0 1 0 0 0 0 0 0 0 0 
0 0 0 2 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 

Tags: Java

Posted by Zeon on Thu, 14 Apr 2022 14:21:47 +0930