4. Arrays

array

This article is to sort out the notes of the Java series course
of Kuangshenshuo .

array definition

  • An array is an ordered collection of data of the same type
  • An array describes several data of the same type, arranged and combined according to a certain sequence
  • Among them, each piece of data is called an array element, and each array element can be accessed through a subscript

Array declaration and creation

  • Array variables must first be declared before the array can be used in the program. Following is the syntax for declaring array variables:

    dataType[] arrayRefVar;		// 首选的方法
    或者
    dataType arrayRefVar[];		// 效果相同,但不是首选方法
    
  • The Java language uses newoperators to create arrays, the syntax is as follows:

    dataType[] arrayRefVar = new dataType[arraySize];
    
  • The elements of the array are accessed by index, and the array index starts from 0

  • Get the length of the array

    arrays.length
    

memory analysis

  • Java memory analysis:
    insert image description here
    Take sample code as an example:
package array;
public class Demo01 {
    public static void main(String[] args) {
        int[] nums;     // 1. 声明一个数组
        nums = new int[10];     // 2. 创建一个数组

        // 3. 给数组中的元素赋值
        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;

        // 计算所有元素的和
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];

        }
        System.out.println(sum);
    }
}

When declaring an array, a space is created in the computer's heap nums, intbut the size of the space is unknown

When creating an array, plan the corresponding space size in the stack of the computer according to the declared type and size,

When assigning values ​​to the elements in the array, the corresponding values ​​are stored in the planned space in the stack

Three kinds of numerical initialization

  • static initialization
int[] a = {
    
    1,2,3};
Man[] mans = {
    
    new Man{
    
    1,1}, new Man{
    
    2,2}};
  • dynamic initialization
int[] a = new int[2];
a[0]=1;
a[1]=2;
  • Default initialization of arrays
  • The array is a reference type, and its elements are equivalent to the instance variables of the class. Therefore, the array has classified space, and each element in it is implicitly initialized in the same way as the instance variable, and has a default value.

Subscript out of bounds and summary

Four basic characteristics of arrays

  • Its length is fixed. Once the array is created, its size cannot be changed.
  • Its elements must be of the same type, mixed types are not allowed
  • The elements in the array can be of any data type, including primitive types and reference types
  • An array variable is a reference type, and an array can also be regarded as an object, and each element in the array is equivalent to a member variable of the object. The array itself is an object, and the object in Java is in the heap, so whether the array saves the original type or other object types, the array object itself is in the heap.

array bounds

  • The legal range of the subscript: [0, length-1], if it exceeds the limit, an error will be reported

    public static void main(String[] args){
          
          
        int[] a = new int[2];
        System.out.println(a[2]);
    }
    
  • Error message: ArrayIndexOutOfBoundException: array subscript 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. Array elements are equivalent to member variables of objects
    • The length of the array is fixed and immutable. If it is out of bounds, an error will be reported.

Multidimensional Arrays

  • A multidimensional array can be regarded as an array of 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 a[][] = new int[2][5];	//定义一个二维数组,其中第一个维度为2个元素,第二个维度为5个元素
    

Arrays class

  • array of utility classesjava.util.Arrays
  • Since the array object itself has no method for us to call, but a tool class Arrays is provided in the API for us to use, so that we can perform some basic operations on the data object
  • View JDK help documentation
  • The methods in the Arrays class are all statically modified static methods, which can be called directly using the class name when in use, and " do not " use the object to call. (Note, it’s not necessary, it’s not impossible)
  • Has the following common functions
    • Assigning values ​​to arrays: via fillmethods
    • Sort the array: by sortmethod, in ascending order
    • Comparing arrays: equalscompare whether the element values ​​in the array are equal by method
    • Find array elements: through binarySearchthe method, the sorted array can be searched by binary classification

Bubble Sort

insert image description here

package array;

/*
冒泡排序
1. 比较数组中相邻两个元素,如果第一个数比第二个数大,则交换两个元素的位置
2. 每一次比较,都会产生出一个最大,或者最小的数字
3. 下一轮则少一次排序
 */

import java.util.Arrays;
public class Demo05 {
    
    
    public static void main(String[] args) {
    
    
        int[] a = {
    
    1,3,345,324,123,14,3,645,6,34,2,34,13412};
        int[] result = sort(a);
        System.out.println(Arrays.toString(result));
    }
    public static int[] sort(int[] array){
    
    
        // 临时变量
        int tmp = 0;
        // 外层循环,判断我们需要走多少次
        for (int i = 0; i < array.length-1; i++) {
    
    
            // 内层循环:比较两个数,如果第一个数比第二个数大,则交换两个元素的位置
            for (int j = 0; j <array.length-1-i ; j++) {
    
    
                if (array[j+1]<array[j]){
    
    
                    tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1]=tmp;
                }
            }
        }
        return array;
    }
}

sparse array

A sparse array is a data structure

  • 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 like this:

    • How many rows and columns are there in the record array, and how many different values ​​are there?
    • Record the elements and rows and values ​​with different values ​​in a small-scale array, thereby reducing the size of the program
  • As shown in the figure below: the left is the original array, and the right is the sparse array
    insert image description here

practise

Compress the specified chessboard with a sparse array and restore it

package 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
 */
public class Demo06 {
    
    
    public static void main(String[] args) {
    
    
        // 1. 创建一个二维数组表示棋盘11*11
        int[][] checkerBoard = new int[11][11];
        // 2. 进行赋值:0:没有棋子,1:黑棋,2:白棋
        checkerBoard[1][2] = 1;
        checkerBoard[2][3] = 2;
        // 输出原始数组
        System.out.println("输出原始数组");
        for (int[] ints : checkerBoard) {
    
    
            for (int anInt : ints) {
    
    
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }

        // 转化为稀疏数组进行保存
        // 1. 统计棋盘中非零个数
        // 2. 统计非零数的索引
        int sum = 0;
        for (int[] ints : checkerBoard) {
    
    
            for (int anInt : ints) {
    
    
                if (anInt != 0 ){
    
    
                    sum++;
                }
            }
        }
        int value = 0;
        int count = 0;
        int[][] array = new int[sum+1][3];
        //稀疏数组的第一行,总行数,总列数,总非零数
        array[0][0] = 11;
        array[0][1] = 11;
        array[0][2] = sum;
        for (int i = 0; i < checkerBoard.length; i++) {
    
    
            for (int j = 0; j < checkerBoard[i].length; j++) {
    
    
                if (checkerBoard[i][j] !=0){
    
    
                    count++;
                    array[count][0] = i;
                    array[count][1] = j;
                    array[count][2] = checkerBoard[i][j];
                }
            }
        }
        // 输出稀疏数组
        System.out.println("输出的稀疏数组为:");
        for (int[] ints : array) {
    
    
            for (int anInt : ints) {
    
    
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }
        System.out.println("=============================");
        System.out.println("稀疏数组的还原:");
        // 1. 读取稀疏数组
        int raw = array[0][0];
        int col = array[0][1];
        // 2. 创建还原数组,并在标记索引位置填充对应值
        int[][] reduction= new int[raw][col];
        for (int i = 1; i <= array[0][2]; i++) {
    
    
            reduction[array[i][0]][array[i][1]]=array[i][2];
        }
        // 3. 打印还原数组
        for (int i = 0; i < reduction.length; i++) {
    
    
            for (int j = 0; j < reduction[i].length; j++) {
    
    
                System.out.print(reduction[i][j]+"\t");
            }
            System.out.println();
        }
    }
}

output:

输出原始数组
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	
输出的稀疏数组为:
11	11	2	
1	2	1	
2	3	2	
=============================
稀疏数组的还原:
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	

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/kakangel/article/details/118528239