Station B [crazy God says Java notes] - array

Posted by drizzle on Wed, 05 Jan 2022 07:12:45 +0100

Crazy God video address

https://www.bilibili.com/video/BV12J41137hu

1. Definition of array

  1. An array is an ordered collection of data of the same type.
  2. Array describes several data of the same type, which are arranged and combined in a certain order.
  3. Among them, each data is called an array element, and each array element accesses them through a subscript.
    3.1. Array subscripts start at 0

2. Array declaration and creation

    add [] after type or [] after array name

dataType  Array name[]  = new dataType[Array length]
dataType[]  Array name   = new dataType[Array length]

int[] nums = new int[10];
nums[0] = 1;
nums[1] = 2;
nums[2] = 3;
nums[3] = 4;
nums[4] = 5;
nums[5] = 6;
nums[6] = 7;
nums[7] = 8;
nums[8] = 9;
nums[9] = 10;

  get array length

System.out.println("The array length is:"+nums.length);
Array length: 10

3.Java memory analysis

heap
  store new objects and arrays
  can be shared by all threads without storing other object references

Stack
   store the basic variable type (including the value of this basic type)
  reference type variable (the specific address where the reference will be stored in the heap)

Method area
  can be shared by all threads
  contains all class and static variables

4. Three initialization methods

1. Static initialization -- create + assign

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

2. Dynamic initialization - including default initialization

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

Dynamic initialization: contains the default initialization of the array
   array is a reference type, and its elements are equivalent to the instance variables of the class. Therefore, the array has allocated space, and each element is implicitly initialized in the same way as the instance variables.

5. Four basic characteristics of array

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

ArrayIndexOutOfBoundsException: array subscript out of bounds exception!

Summary:

  1. An array is an ordered collection of the same data type
  2. Arrays are also objects. An array element is equivalent to a member variable of an object
  3. The array length is fixed and cannot be changed.

6. Find the maximum value of the array

public static void main(String[] args) {
    int[] nums = {1, 5, 2, 39, 2, 5, 72, 24};
    int max = nums[0];
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] > max){
            max = nums[i];
        }
    }
    System.out.println("The maximum value of the array is:"+max);
}

7. Print array

public static void main(String[] args) {
    int[] nums = {1, 5, 2, 39, 2, 5, 72, 24};
    for (int i : nums){
        System.out.print(i+" ");
    }
    System.out.println();
    System.out.println("===================");
    for (int i = 0;i<nums.length;i++){
        System.out.print(nums[i]+" ");
    }
}

8. Invert array

public static void main(String[] args) {
    int[] nums = {1, 5, 2, 39, 2, 5, 72, 24};
    for (int i = nums.length - 1; i >= 0; i--) {
        System.out.print(nums[i] + " ");
    }
}

9. 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.

  two dimensional array

int[][] arr = new int[3][2]
Defines an array of 3 rows and 2 columns

10.Arrays class

  1. Array tool class java utils. Arrays
  2. There are no methods for the array object itself, but the API provides a tool class Arrays for us to use, so we can perform some basic operations on the data object.
  3. The methods in the Arrays class are static methods decorated with static, which can be called directly with the class name.
  4. It has the following common functions
    4.1. Assign a value to the array: through the fill method
    4.2. Sort the array: sort in ascending order through the sort method
    4.3. Compare arrays: use the equals method to compare whether the element values in the array are equal
    4.4. Find array elements: binary search the sorted array through the binarySearch method

Arrays.toString implementation

public static String toString(int[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

11. Bubble sorting

Bubble sorting is undoubtedly one of the most famous sorting algorithms. There are eight sorting algorithms in total!
  bubble sorting, two-layer circulation, the number of bubble rounds in the outer layer and the inner layer are compared in turn, which is well known in the Jianghu!

public static void main(String[] args) {
    int[] arr = {1, 23, 6, 6, 2, 2, 23, 34, 5};
    //1. Compare two adjacent elements in the array. If the first number is greater than the second number, the interactive position will be determined
    //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!
    System.out.println(Arrays.toString(arr));
    sort(arr);
    System.out.println(Arrays.toString(arr));
}

public static void sort(int[] arr) {
    //Outer circle, judge how many times we have to go
    for (int i = 0; i < arr.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 < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j+ 1];
                arr[j + 1] = temp;
            }
        }
    }
}

12. Sparse array

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


   sparse arrays are processed 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-scale array, so as to reduce the size of the program

! [insert picture description here]( https://img-blog.csdnimg.cn/c205f62c3e3f4d39b276f71652f08deb.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQyMDI1Nzk4,size_16,color_FFFFFF,t_70#pic_center)

console output

Original 2D array
======================
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	
The valid values of two-dimensional array are: 2
 Convert to sparse array
================================
11	11	2	
1	2	1	
2	3	2	
================
reduction
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	

All codes

package cn.bloghut.demo1;

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;

/**
 * @author by balderdash
 * @classname P1
 * @description TODO
 * @date 2021/7/22 10:13
 */
public class P1 {
    public static void main(String[] args) {
        //Create a two-dimensional array of 11 * 11. 0 is the default, 1 is white and 2 is black
        int[][] arr = new int[11][11];
        arr[1][2] = 1;
        arr[2][3] = 2;
        //Print 2D array
        System.out.println("Original 2D array======================");
        print(arr);
        //Gets the valid value of the dimension group
        int sum = 0;
        for (int[] ints : arr) {
            for (int anInt : ints) {
                if (anInt != 0) {
                    sum++;
                }
            }
        }
        System.out.println("Valid values for a two-dimensional array are:" + sum);
        //Building sparse arrays
        int[][] arr2 = new int[sum + 1][3];
        arr2[0][0] = 11;
        arr2[0][1] = 11;
        arr2[0][2] = sum;
        int count = 0;
        //Traverse the two-dimensional array and assign values to the sparse array
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != 0) {
                    count++;
                    arr2[count][0] = i;
                    arr2[count][1] = j;
                    arr2[count][2] = arr[i][j];
                }
            }
        }
        System.out.println("Convert to sparse array================================");
        print(arr2);
        //reduction
        System.out.println("================");
        System.out.println("reduction");

        int[][] arr3 = new int[arr2[0][0]][arr2[0][1]];
        for (int i = 1; i < arr2.length; i++) {
            arr3[arr2[i][0]][arr2[i][1]] = arr2[i][2];
        }
        print(arr3);
    }

    /**
     * Print 2D array
     *
     * @param arr
     */
    public static void print(int[][] arr) {
        String str = "[ ";
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Topics: Java Programming array