03-The use of java array

concept

An array is a container that stores data with a fixed length, and the data types for storing multiple data must be consistent.

Array definition format

// 第一种格式
// 数据类型[] 数组名
int[] arr;        
double[] arr;      
char[] arr;

// 第二种格式
// 数据类型 数组名[]
int arr[];
double arr[];
char arr[];

Dynamic initialization of arrays

What is dynamic initialization

The dynamic initialization of the array means that only the length of the array is given, and the default initialization value is given by the system

Dynamic initialization format

数据类型[] 数组名 = new 数据类型[数组长度];
int[] arr = new int[3];

Detailed dynamic initialization format

  • To the left of the equal sign:

    • int: the data type of the array

    • []: Indicates that this is an array

    • arr: represents the name of the array

  • Right side of the equal sign:

    • new: open up memory space for the array
    • int: the data type of the array
    • []: Indicates that this is an array
    • 5: Represents the length of the array

code :

package com.itheima.array;

public class Demo2Array {
    
    
    /*
        数组的动态初始化:
            在初始化的时候, 需要手动指定数组的长度, 系统会为数组容器分配初始值.

        动态初始化格式:
            数据类型[] 数组名 = new 数据类型[数组的长度];

        注意:
            打印数组变量的时候, 会打印出数组的内存地址

        [I@10f87f48 :
                        @ : 分隔符
                        [ : 当前的空间是一个数组类型
                        I : 当前数组容器中所存储的数据类型
                        10f87f48 : 十六进制内存地址
                                0 1 2 3 4 5 6 7 8 9 a b c d e f
     */
    public static void main(String[] args) {
    
    
        // 数据类型[] 数组名 = new 数据类型[数组的长度];
        // 通过new关键字创建了一个int类型的数组容器, 该容器可以存储5个int类型的整数, 该容器被arr数组变量所记录
        int[] arr = new int[5];
        // [I@10f87f48
        System.out.println(arr);

        byte[] bArr = new byte[3];
        // [B@b4c966a
        System.out.println(bArr);

    }
}

Static initialization of arrays

What is static initialization

When creating an array, determine the elements directly

static initialization format

完整版格式  
数据类型[] 数组名 = new 数据类型[]{
    
    元素1,元素2,...};

简化版格式  
数据类型[] 数组名 = {
    
    元素1,元素2,...};

Array element access

what is index

Each element stored in the array will automatically have a number, starting from 0.

This automatic number is called the array index (index), and the elements in the array can be accessed through the index of the array.

access array element format

数组名[索引];

memory overview

Memory is an important original in the computer, a temporary storage area, and its function is to run programs.

The programs we write are stored in the hard disk, and the programs in the hard disk will not run.

It must be placed in the memory to run, and the memory will be cleared after the operation is completed.

To run programs, the Java virtual machine must allocate and manage memory space.

Two common problems with array operations

Index out of bounds exception

  • Cause
    The length of the array is 3, and the index range is 0~2, but we have accessed an index of 3.
    After the program runs, it will throw an ArrayIndexOutOfBoundsException array out of bounds exception. In development, the out-of-bounds exception of the array cannot appear. Once it occurs, the code we write must be modified.
public class ArrayDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = new int[3];
        System.out.println(arr[3]);
    }
}
  • Solution
    Change the wrong index to the correct index range!

null pointer exception

  • The reason
    arr = null This line of code means that the variable arr will not save the memory address of the array, and it is not allowed to operate the array, so a NullPointerException will be thrown when running. In development, null pointer exceptions cannot occur. Once it occurs, the code we write must be modified.
public class ArrayDemo {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = new int[3];

        //把null赋值给数组
        arr = null;
        System.out.println(arr[0]);
    }
}
  • Solution
    Just give the array a real heap memory space reference!

Array common operations

array traversal

  • Array traversal: It is to get each element in the array separately, which is traversal. Traversal is also the cornerstone of array manipulation.
  • In fact, there are two types of traversal, objects and arrays. It’s just which traversal applies to which, and I will summarize it later
package com.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class demo {
    
    
    public static void main(String[] args) {
    
    
       // 数组遍历方式
        String[] arrs = {
    
    "a", "b", "c"};

        // for
        for (int i = 0; i < arrs.length; i++) {
    
    
            System.out.println(arrs[i]);
        }
        System.out.println("================");

        // for增强
        for (String str : arrs) {
    
    
            System.out.println(str);
        }
        System.out.println("================");

        // Iterator(迭代器)
        Iterator<String> iterator = Arrays.stream(arrs).iterator();
        while (iterator.hasNext()){
    
    
            String next = iterator.next();
            System.out.println(next);
        }
        System.out.println("================");

        //stream
        Arrays.stream(arrs).forEach(System.out::println);

        // Arrays
        System.out.println(Arrays.toString(arrs));
    }
}

Array filter/find

common filter

Code:

public static void main(String[] args) {
    
    
    String[] arrs = {
    
    "a", "b", "c"};
    for (String arr : arrs) {
    
    
        if(!"a".equals(arr)){
    
    
            System.out.println("打印出不是a的值:"+ arr);
        }
    }
}

binary search (comprehension)

Note: There is a prerequisite that the elements in the array must be arranged in order of size . If there is no order of size, the binary search method cannot be used

Binary Search Overview

  • When looking for the position of the specified element in the array, the previous method is to traverse and get each element one by one to see if it is the element to be searched. When the array has many elements, the search efficiency is very low.
  • Binary search is also called half search, which can remove half of the search range each time, thereby improving the efficiency of search

need

  • Find the position of an element in the array {1,2,3,4,5,6,7,8,9,10}

Implementation steps

  1. Define two variables that represent the range to look for. Default min = 0, max = maximum index
  2. Loop search, but min <= max
  3. Calculate the value of mid
  4. Determine whether the element at the mid position is the element to be searched, if it is, directly return the corresponding index
  5. If the value to be found is on the left half of mid, then the min value remains unchanged, max = mid -1. Continue to search for the next cycle
  6. If the value to be found is on the right half of mid, then the max value remains unchanged, min = mid + 1. Continue to search for the next cycle
  7. When min > max, it means that the element to be searched does not exist in the array, and returns -1.

Code

public class MyBinarySearchDemo {
    
    
    public static void main(String[] args) {
    
    
        int [] arr = {
    
    1,2,3,4,5,6,7,8,9,10};
        int number = 11;

        //1,我现在要干嘛? --- 二分查找
        //2.我干这件事情需要什么? --- 数组 元素
        //3,我干完了,要不要把结果返回调用者 --- 把索引返回给调用者
        int index = binarySearchForIndex(arr,number);
        System.out.println(index);
    }

    private static int binarySearchForIndex(int[] arr, int number) {
    
    
        //1,定义查找的范围
        int min = 0;
        int max = arr.length - 1;
        //2.循环查找 min <= max
        while(min <= max){
    
    
            //3.计算出中间位置 mid
            int mid = (min + max) >> 1;
            //mid指向的元素 > number
            if(arr[mid] > number){
    
    
                //表示要查找的元素在左边.
                max = mid -1;
            }else if(arr[mid] < number){
    
    
                //mid指向的元素 < number
                //表示要查找的元素在右边.
                min = mid + 1;
            }else{
    
    
                //mid指向的元素 == number
                return mid;
            }
        }
        //如果min大于了max就表示元素不存在,返回-1.
        return -1;
    }
  
}

data sorting

Bubble Sort

step

Compare adjacent elements. If the first is bigger than the second, swap them both.

Animation presentation

img

Code

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3,4,1,2};
        int[] ints = bubbleSort(arr);
        Arrays.stream(ints).forEach(System.out::println);
        
        System.out.println(Arrays.toString(bubbleSort(arr)));
    }


    // 返回一个对原数组没有影响的排好序的新数组
    public static int[] bubbleSort(int[] sourceArray)   {
    
    
        // 对 arr 进行拷贝,不改变参数内容
        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);

        for (int i = 1; i < arr.length; i++) {
    
    
            for (int j = 0; j < arr.length - i; j++) {
    
    
                if (arr[j] > arr[j + 1]) {
    
    
                    int tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                }
            }
        }
        return arr;
    }
}

selection sort

step

  1. First find the smallest (largest) element in the unsorted sequence and store it at the beginning of the sorted sequence.
  2. Then continue to find the smallest (largest) element from the remaining unsorted elements, and then put it at the end of the sorted sequence .

Animation presentation

img

Code

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3,4,1,2};
        int[] ints = selectSort(arr);
        Arrays.stream(ints).forEach(System.out::println);
    }

    public static int[] selectSort(int[] arrs){
    
    
        int minIndex,temp;
        for (int i = 0; i < arrs.length-1; i++) {
    
      // 注意,这里需要减一
            minIndex = i; // 默认最小值元素的索引
            for (int j = i+1; j < arrs.length; j++) {
    
    
                if(arrs[minIndex] > arrs[j]){
    
      // 依次查找最小值的索引
                    minIndex = j;
                }
            }
            if(minIndex != i){
    
       // 如果最小值的索引不一样,交换位置
                temp = arrs[minIndex];
                arrs[minIndex] = arrs[i];
                arrs[i] = temp;
            }
        }
        return arrs;
    }
}

insertion sort

step

Treat the first element of the first sequence to be sorted as an ordered sequence, and treat the second element to the last element as an unsorted sequence.

Scans the unsorted sequence sequentially from beginning to end, and inserts each scanned element into its proper position in the sorted sequence. (If the element to be inserted is equal to an element in the ordered sequence, the element to be inserted is inserted after the equal element.

To be honest, it’s a bit confusing. According to my understanding, for example, playing cards, how do we sort the cards when we play cards?

  1. take a card from all cards
  2. Take the card for the second time, compare it with the one in the first chapter, and then sort
  3. For the third time, compare it with the previous two cards and insert it into the designated position. . .
  4. For the last time, get the last card, compare it with the card in your hand, and insert it into the designated position

Animation presentation

img

Code

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    3,4,1,2};
        int[] ints = insertSort(arr);
        Arrays.stream(ints).forEach(System.out::println);
    }

    public static int[] insertSort(int[] sourceArray) {
    
    
        // 对 arr 进行拷贝,不改变参数内容
        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);

        // 从下标为1的元素开始选择合适的位置插入,因为下标为0的只有一个元素,默认是有序的
        for (int i = 1; i < arr.length; i++) {
    
    

            // 记录要插入的数据
            int tmp = arr[i];

            // 从已经排序的序列最右边的开始比较,找到比其小的数
            int j = i;
            while (j > 0 && tmp < arr[j - 1]) {
    
    
                arr[j] = arr[j - 1];
                j--;
            }

            // 存在比其小的数,插入
            if (j != i) {
    
    
                arr[j] = tmp;
            }

        }
        return arr;
    }
}

Array element sum/string concatenation

    public static void main(String[] args) {
    
    
        // 求和
        int[] arr = {
    
    1,2,3,4};
        int total = 0;
        for (int i : arr) {
    
    
            total += i;
        }
        System.out.println("合为:"+total);

        String[] strs = {
    
    "a","b","c","d"};
        String str = "";
        for (String s : strs) {
    
    
            str += s;
        }
        System.out.println("拼接后的字符串为:"+str);
    }

array get maximum value

  • Maximum value acquisition: Find the maximum value from all elements of the array.

  • Implementation idea:

    • Define a variable to save the element at index 0 of the array
    • Traverse the array and get each element in the array
    • Compare the traversed element with the variable holding the value at index 0 of the array
    • If the value of the array element is greater than the value of the variable, the variable records the new value
    • After the loop traversal of the array ends, the variable saves the maximum value in the array
  • Code:

package com.itheima.test;

import java.util.Scanner;

public class Test2Array {
    
    
    /*
        需求: 从数组中查找最大值

                int[] arr = {12,45,98,73,60};

        实现步骤:
                1. 假设数组中的第一个元素为最大值
                2. 遍历数组, 获取每一个元素, 准备进行比较
                3. 如果比较的过程中, 出现了比max更大的, 让max记录更大的值
                4. 循环结束后, 打印最大值.
     */
    public static void main(String[] args) {
    
    
        int[] arr = {
    
    12,45,98,73,60};
        // 1. 假设数组中的第一个元素为最大值
        int max = arr[0];
        // 2. 遍历数组, 获取每一个元素, 准备进行比较
        for(int i = 1; i < arr.length; i++){
    
    
            // 3. 如果比较的过程中, 出现了比max更大的, 让max记录更大的值
            if(arr[i] > max){
    
    
                max = arr[i];
            }
        }
        //  4. 循环结束后, 打印最大值.
        System.out.println("max:" + max);
    }
}

Arrays (application)

Common methods of Arrays

method name illustrate
public static String toString(int[] a) Returns a string representation of the contents of the specified array
public static void sort(int[] a) Arranges the specified array in numerical order
public static int binarySearch(int[] a, int key) Returns the index of the specified element using binary search

sample code

public class MyArraysDemo {
    
    
      public static void main(String[] args) {
    
    
  //        public static String toString(int[] a)    返回指定数组的内容的字符串表示形式
  //        int [] arr = {3,2,4,6,7};
  //        System.out.println(Arrays.toString(arr));

  //        public static void sort(int[] a)      按照数字顺序排列指定的数组
  //        int [] arr = {3,2,4,6,7};
  //        Arrays.sort(arr);
  //        System.out.println(Arrays.toString(arr));

  //        public static int binarySearch(int[] a, int key) 利用二分查找返回指定元素的索引
          int [] arr = {
    
    1,2,3,4,5,6,7,8,9,10};
          int index = Arrays.binarySearch(arr, 0);
          System.out.println(index);
          //1,数组必须有序
          //2.如果要查找的元素存在,那么返回的是这个元素实际的索引
          //3.如果要查找的元素不存在,那么返回的是 (-插入点-1)
              //插入点:如果这个元素在数组中,他应该在哪个索引上.
      }
  }
  • tool design ideas
    1. The constructor is modified with private
    2. Members are decorated with public static

2D Array Overview

Overview: A two-dimensional array is also a kind of container. Unlike a one-dimensional array, the container stores all one-dimensional array containers

Two-dimensional array dynamic initialization

动态初始化格式:

数据类型[][] 变量名 = new 数据类型[m][n];
m表示这个二维数组,可以存放多少个一维数组
n表示每一个一维数组,可以存放多少个元素
package com.itheima.demo;

public class Demo1Array {
    
    
    /*
        动态初始化格式:

            数据类型[][] 变量名 = new 数据类型[m][n];
            m表示这个二维数组,可以存放多少个一维数组
            n表示每一个一维数组,可以存放多少个元素
     */
    public static void main(String[] args) {
    
    
        // 数据类型[][] 变量名 = new 数据类型[m][n];
        int[][] arr = new int[3][3];
        /*
            [[I@10f87f48

            @ : 分隔符
            10f87f48 : 十六进制内存地址
            I : 数组中存储的数据类型
            [[ : 几个中括号就代表的是几维数组
         */
        System.out.println(arr);

        /*
            二维数组存储一维数组的时候, 存储的是一维数组的内存地址
         */
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);

        System.out.println(arr[0][0]);
        System.out.println(arr[1][1]);
        System.out.println(arr[2][2]);

        // 向二维数组中存储元素
        arr[0][0] = 11;
        arr[0][1] = 22;
        arr[0][2] = 33;

        arr[1][0] = 11;
        arr[1][1] = 22;
        arr[1][2] = 33;

        arr[2][0] = 11;
        arr[2][1] = 22;
        arr[2][2] = 33;

        // 从二维数组中取出元素并打印
        System.out.println(arr[0][0]);
        System.out.println(arr[0][1]);
        System.out.println(arr[0][2]);
        System.out.println(arr[1][0]);
        System.out.println(arr[1][1]);
        System.out.println(arr[1][2]);
        System.out.println(arr[2][0]);
        System.out.println(arr[2][1]);
        System.out.println(arr[2][2]);
    }
}

Two-dimensional array static initialization

Code :

package com.itheima.demo;

public class Demo3Array {
    
    
    /*
        完整格式:数据类型[][] 变量名 = new 数据类型[][]{ {元素1, 元素2...} , {元素1, 元素2...} ...};

        简化格式: 数据类型[][] 变量名 = { {元素1, 元素2...} , {元素1, 元素2...} ...};
     */
    public static void main(String[] args) {
    
    
        int[] arr1 = {
    
    11,22,33};
        int[] arr2 = {
    
    44,55,66};

        int[][] arr = {
    
    {
    
    11,22,33}, {
    
    44,55,66}};
        System.out.println(arr[0][2]);

        int[][] array = {
    
    arr1,arr2};
        System.out.println(array[0][2]);
    }
}

2D array traversal

need :

Known a two-dimensional array arr = { {11, 22, 33}, {33, 44, 55}};

Iterate through the array, fetch all elements and print

steps:

  1. Traverse the two-dimensional array and take out each one-dimensional array inside

  2. During the traversal process, continue to complete the traversal of each one-dimensional array, and obtain each element of the internal storage

Code :

package com.itheima.test;

public class Test1 {
    
    
    /*
        需求:

            已知一个二维数组 arr = {
    
    {11, 22, 33}, {33, 44, 55}};
            遍历该数组,取出所有元素并打印

        步骤:
            1. 遍历二维数组,取出里面每一个一维数组
            2. 在遍历的过程中,对每一个一维数组继续完成遍历,获取内部存储的每一个元素
     */
    public static void main(String[] args) {
    
    
        int[][] arr = {
    
    {
    
    11, 22, 33}, {
    
    33, 44, 55}};

        // 1. 遍历二维数组,取出里面每一个一维数组
        for (int i = 0; i < arr.length; i++) {
    
    
            //System.out.println(arr[i]);
            // 2. 在遍历的过程中,对每一个一维数组继续完成遍历,获取内部存储的每一个元素
            //int[] temp = arr[i];
            for (int j = 0; j < arr[i].length; j++) {
    
    
                System.out.println(arr[i][j]);
            }
        }
    }
}

2D array sum

need :

某公司季度和月份统计的数据如下:单位(万元)
第一季度:22,66,44
第二季度:77,33,88
第三季度:25,45,65
第四季度:11,66,99

steps:

  1. Define the summation variable and prepare to record the final accumulation result
  2. Use a two-dimensional array to store data, each quarter is a one-dimensional array, and then assemble four one-dimensional numbers
  3. Traverse a two-dimensional array, get all elements, accumulate and sum
  4. Output the final result

Code :

package com.itheima.test;

public class Test2 {
    
    
    /*
        需求:
            某公司季度和月份统计的数据如下:单位(万元)
            第一季度:22,66,44
            第二季度:77,33,88
            第三季度:25,45,65
            第四季度:11,66,99

        步骤:
            1. 定义求和变量,准备记录最终累加结果
            2. 使用二维数组来存储数据,每个季度是一个一维数组,再将4个一维数组装起来
            3. 遍历二维数组,获取所有元素,累加求和
            4. 输出最终结果
     */
    public static void main(String[] args) {
    
    
        // 1. 定义求和变量,准备记录最终累加结果
        int sum = 0;
        // 2. 使用二维数组来存储数据,每个季度是一个一维数组,再将4个一维数组装起来
        int[][] arr = {
    
     {
    
    22,66,44} , {
    
    77,33,88} , {
    
    25,45,65} , {
    
    11,66,99}};
        // 3. 遍历二维数组,获取所有元素,累加求和
        for (int i = 0; i < arr.length; i++) {
    
    
            for(int j = 0; j < arr[i].length; j++){
    
    
                sum += arr[i][j];
            }
        }
        // 4. 输出最终结果
        System.out.println(sum);
    }
}

Guess you like

Origin blog.csdn.net/weixin_44797182/article/details/130288277