Crazy God says Java: array notes

catalogue

I Array overview

II Array declaration creation

1. Array declaration

2. Memory analysis

 3. Three kinds of initialization

1. Static initialization:

2. Dynamic initialization

4. Four basic characteristics of arrays:

 5. Array boundary

III Array usage

IV Multidimensional array

V Arrays class

Bubble sort:

Vi Sparse array

I Array overview

An array is an ordered collection of data of the same 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 a subscript

II Array declaration creation

1. Array declaration

Array variables must be declared before they can be used in programs. The following is the syntax for declaring array variables

dataType[] arrayRefVar;//Preferred method
 or
dataType arrayRefVar[];//Same effect, but not preferred
//Example of data type array name: int array1 [];

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

dataType[] arrayrefVar = new dataType[arraySize];

The elements of the array are accessed through the index. The array index starts from 0

Get array length: arrays length

//Type of variable name of variable = value of variable;
        //Array type

        int[] nums;  //Declare an array

        nums = new int[10];//Create an array

        //int[] nums = new int[10];    Declare and create

        for (int i = 0; i < nums.length; i++) {
            nums[i] = i+1;

        }
        //Assign values to array elements
        //Calculate the sum of all elements
        int sum =0;
        //Get array length: array length
        for (int a = 0; a < nums.length; a++) {
            sum+=nums[a];

        }
        System.out.println("The sum is:"+sum);//Total: 55

2. Memory analysis

 

 3. Three kinds of initialization

1. Static initialization:

int[] a = {1,2,3};

2. Dynamic initialization

int[] a = new int[2]; 
a[0] = 1;
a[1] = 2;

Default initialization of array:

Array is a reference type, and its elements are equivalent to the instance variables of the class. Therefore, once the array is allocated space, each element in it is implicitly initialized in the same way as the instance variables.

//Static initialization: create + assign
        int[]a = {1,2,3,4,5,6,7,8};
        System.out.println(a[0]);// 1

        //Dynamic initialization: contains default initialization
        int b[] = new int[10];
        b[0] = 10;
        b[1] = 12;

        System.out.println(b[0]);// 10
        System.out.println(b[1]);// 12
        System.out.println(b[2]);// 0
        System.out.println(b[3]);// 0

4. Four basic characteristics of arrays:

1. Its length is determined. Once an array is created, its size cannot be changed.

2. Its array elements must be of the same type, and mixed types are not allowed.

3. The elements in the array can be any data type, including basic type and reference type.

4. Array variable belongs to reference type, and array can also be regarded as variable. Each element in the array is equivalent to the member variable of the object. The array itself is an object, and the Java object is in the heap. Therefore, the array itself is in the heap whether it saves the original type or other object types.

 5. Array boundary

The legal range of the subscript: [0,length-1]. If it exceeds the range, an error will be reported;

public static void main(String[] args) {
        int[] a = new int[2];
        System.out.println(a[2]);
}

ArrayIndexOutOfBoundsException: array index out of bounds exception

Summary:

An array is an ordered collection of the same data type (the data type can be any type)

Arrays are also objects. An array element is equivalent to a member variable of an object

The array length is fixed and immutable. If the boundary is exceeded, an error is reported: ArrayIndexOutOfBounds

III Array usage

1. Ordinary For loop

2. For each cycle

int[] array = {1,2,3,4,5};
        //Print all array elements
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]); // 1 2 3 4 5
        }
        System.out.println("===============================");
        //Calculate the sum of all elements
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum+=array[i];
        }
        System.out.println("sum="+sum);// sum = 15
        System.out.println("==================================");
        //Find maximum element
        int max =array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i]>max){
                max = array[i];
            }
        }
        System.out.println("max = "+max);// max = 5

    }

3. Array method input parameters

4. Array as return value

 int[] arrays = {1,2,3,4,5};
        //jdk1.5 No subscript
//        for (int array : arrays) {
//            System.out.println(array);
//        }

        printArray(arrays);// 1 2 3 4 5
        System.out.print("=========================");
        int[] reverse = reverse(arrays);
        printArray(reverse);// 5 4 3 2 1 
    }
    //Invert array
    public static int[] reverse(int[] arrays) {
        int[] result = new int[arrays.length];
        //Reverse operation
        for (int i = 0,j = result.length-1; i < arrays.length ; i++,j--) {
            result[j] = arrays[i];
            
        }
        return result;

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

        }

    }

IV 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

2D array:

int a [][] = new int[2][5];

Analysis: the above array a can be regarded as an array with two rows and five columns

 //[4] [2] object oriented
        /*
         1,2            array[0]
         2,3            array[1]
         3,4            array[2]
         4,5            array[3]
         */
        int [][] array = {{1,2},{2,3},{3,4},{4,5}};

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.println(array[i][j]);
              //1 2 2 3 3 4 4 5
                
            }
            
        }

V Arrays class

Array tool class java util. Arrays

There are no methods for us to call array objects, but the API provides a tool class Arrays for us to use, so we can perform some basic operations on data objects

View JDK help documentation: link: https://pan.baidu.com/s/1CimcwVTrbWrLlePr6jC0WA  
Extraction code: om7h

All the methods in the Arrays class are static methods decorated with static. When using them, you can call them directly with the class name instead of using the object (note that "don't use" instead of "can't")

It has the following common functions:

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 the binarySearch method

package com.tfs.array;


import java.util.Arrays;

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

        int[] a ={133,23,3,15,68,98,520};

        System.out.println(a);//[I@14ae5a5
        //Print array element arrays toString
        System.out.println(Arrays.toString(a));//[133, 23, 3, 15, 68, 98, 520]

        printArrays(a);
        System.out.println("\n");//[133, 23, 3, 15, 68, 98, 520]

        Arrays.sort(a);//Array sorting: ascending
        System.out.println(Arrays.toString(a));//[3, 15, 23, 68, 98, 133, 520]

        Arrays.fill(a,2,4,0);//The number of the 3rd to 5th numbers in the array filling array is set to 0
        System.out.println(Arrays.toString(a));//[3, 15, 0, 0, 98, 133, 520]
    }

    public static void printArrays(int[] a) {
        for (int i = 0; i < a.length; i++) {
            if (i==0){
                System.out.print("[");
            }
            if (i==a.length-1){
                System.out.print(a[i]+"]");
            }else{
                System.out.print(a[i]+", ");
            }
        }

    }
}

Bubble sort:

Bubble sorting is undoubtedly one of the most famous sorting algorithms, with a total of eight sorting algorithms

The bubbling sequence is relatively simple, with two-layer circulation, the number of bubbling wheels in the outer layer and the inner layer in turn

When we see nested loops, we should immediately get that the time complexity of this algorithm is O(n2)

package com.tfs.array;

import java.util.Arrays;
//Bubble sorting
//1. Compare two adjacent elements in the array. If the first number is larger than the second, we exchange their positions
//2. Each comparison will produce a maximum or minimum number
//3. The next round can be sorted one less time
//4. Cycle successively until the end
public class ArrayDemo07 {
    public static void main(String[] args) {

        int[] a = {1,6,5,4,8,23,54,12,47,54};
        int[] sort = sort(a);
        //After calling our own sorting method, we return a sorted array
        System.out.println(Arrays.toString(sort));
  //  [54, 54, 47, 23, 12, 8, 6, 5, 4, 1]
    }



    public static int[] sort(int[] array){
        //Temporary variable
        int temp = 0;
        //Outer circle, judge how many times to go
        for (int i = 0; i < array.length-1; i++) {
            //The inner loop compares and judges two numbers. If the first number is larger than the second number, the position is exchanged
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j+1]>array[j]){
                    temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }

        }
        return array;

    }
}

Vi Sparse array

When most elements in an array are 0 or an array with the same value, you can save the array with a sparse 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 elements, rows, columns and values with different values in a small array, so as to reduce the size of the program

As shown in the figure, the original array is on the left and the sparse array is on the right

 

 int[][] array1 = new int[11][11];
//Create a binary array 11 * 11 0: no pieces 1: Black 2: white
        array1[1][2] = 1;
        array1[2][3] = 2;
        //Output original array
        System.out.println("Output original array:");

        for (int[] ints : array1) {
            for (int anInt : ints) {
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }
       

Output results:

 

Convert original array to sparse array:

 //Convert to sparse array save
        //Get the number of valid values
        int sum = 0;
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                if (array1[i][j]!=0){
                    sum++;
                }
                
            }
            
        }
        System.out.println("The number of valid values is:"+sum);
        //Create an array of sparse arrays
        int[][] array2 = new int[sum + 1][3];
        array2[0][0] = array1.length;
        array2[0][1] = array1[0].length;
        array2[0][2] = sum;

        int count = 0;
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {
                if (array1[i][j]!=0){
                    count++;
                    array2[count][0] = i;
                    array2[count][1] = j;
                    array2[count][2] = array1[i][j];
                }
            }
        }
        System.out.println("Sparse array:");

        for (int i = 0; i < array2.length; i++) {
            System.out.println(array2[i][0]+"\t"
                    + array2[i][1]+"\t"
                    + array2[i][2]+"\t");
        }

Output results:

Restore sparse array to original array:

  System.out.println("reduction");
        //1. Read sparse array
        int[][] array3 = new int[array2[0][0]][array2[0][1]];
        //2. Restore its value to the element in it
        for (int i = 1; i < array2.length; i++) {
            array3[array2[i][0]][array2[i][1]] = array2[i][2];
        }
        //3. Printing
        System.out.println("Output restored array:");
        for (int[] ints : array1) {
            for (int anInt : ints) {
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }

Output results:

Keywords: Java

Added by FaT3oYCG on Fri, 24 Dec 2021 16:50:17 +0200