Java basic learning 04 (Java array)


The notes and pictures in the article are from watching this video:
Crazy God says Java

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 according to a certain order.
  3. Each of these data is called an array element, and each array element can access them through a subscript.

Example: pandas is a NumPy based tool created to solve data analysis tasks.

2, Array declaration creation

  • Array variables must be declared before arrays can be used in programs. The following is the syntax for declaring array variables:
dataType[] arrayRefVar; //Preferred method
dataType arrayRefVar[]; //The same effect, but not the preferred method
  • The Java language uses the new operator to create arrays. The syntax is as follows:
dataTypeRefVar = new dataType[arrySize];
  • Array elements are accessed by index. The array index starts from 0.
  • Get array length: arrays length

3, Initialization of array

  • initiate static
//Static initialization: create + assign
int[] a={1,2,3,4,5,6,7};
  • dynamic initialization
//Dynamic initialization: contains default initialization
int[] b=new int[10];
  • Default initialization of arrays
    Array is a reference type. Its elements are equivalent to the real column variables of the class. Therefore, once the array is allocated space, each element in it is implicitly initialized in the way of real column variables.

4, Four basic characteristics of arrays

  • 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.
  • The elements in the array can be any data type, including basic types and reference types.
  • 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.

5, Array boundary

  • The legal range of the subscript: [0,length-1]. If it exceeds the range, an error will be reported;
  • ArrayIndexOutOfBoundsException: 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. An array element is equivalent to a member variable of an object
    The array length is fixed and immutable. If the boundary is exceeded, it will report: ArrayIndexOutOfBounds

6, Use of arrays

  • Normal for loop
  • For each loop
  • Array as method input parameter
  • Array as return value
package array;

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

        //Print all array elements
        for (int i = 0; i < arrays.length; i++) {
        //Calculate the sum of all elements
        int sum=0;
        for (int i = 0; i < arrays.length; i++) {
        //Find maximum element
        int max=arrays[0];

        for (int i = 0; i < arrays.length; i++) {

7, Multidimensional array

  1. 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.
  2. Two dimensional array
int a[][]=new[2][5]

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

package array;

public class ArrayDemo05 {
    public static void main(String[] args) {
        * 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++) {


8, Arrays class

  • Array tool class java util. arrays
  • Since there are no methods for us to call array objects, a tool class Arrays is provided in the single API for us to use, so that we can perform some basic operations on data objects,
  • View KJDK help documentation
  • 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 objects (Note: they are "not used" instead of "cannot").
  • 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 array of sorting numbers through the bianrySearch method.
package array;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ArrayDemo06 {
    public static void main(String[] args) {
        int[] a={1,2,34,56,78,90,23,11,78};


        //Print array elements
//        System.out.println(Arrays.toString(a));
        Arrays.sort(a);//Sort array
    public static void printArray(int[] a){
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]+" ");

9, Bubble sorting

package array;

import java.util.Arrays;

public class ArrayDemo07 {
    public static void main(String[] args) {
        int[] b={1,35,67,55,22,11,45};
        int[] sort=sort(b);


    //Bubble sorting
    //1. Compare two adjacent elements in the array. If the first number is larger than the second number, we will exchange their positions
    //2. Each comparison will produce a maximum or minimum number;
    //3. The next round can be sorted less once!
    //4. Cycle successively until the end!

    public static int[] sort(int[] array){
        //Temporary variable
        int temp=0;

        //Outer circle, judge how many times we have to go;
        for (int i = 0; i < array.length; 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++) {


        return array;

10, Sparse matrix

1. Introduction to 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 handled as follows:
    How many rows and columns are there in the record array? How many different values are there
    The elements, rows, columns and values with different values are recorded in a small-scale array, so as to reduce the size of the program

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

6, 7 and 8 in [0] indicate that this is an array of 6 rows and 7 columns, with 8 different numbers except 0;
[1] The number inside indicates that the number in row 0 and column 3 is 22

  • Write a sparse array based on this chessboard
package array;

public class ArrayDemo08 {
    public static void main(String[] args) {
        //1. Create a two-dimensional array 11 * 11 0: no chess pieces, 1: black chess, 2: white chess
        int[][] array1=new int[11][11];
        //Output raw array
        System.out.println("Output raw array");
        for (int[] ints : array1) {
            for (int anInt : ints) {

        //Convert to sparse array save
        //Get the number of valid values
        int sum=0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {

        System.out.println("Number of valid values:"+sum);

        //2. Create an array of sparse arrays
        int[][] array2=new int[sum+1][3];

        //Traverse a two-dimensional array and store non-zero values in a sparse array
        int count=0;
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array1[i].length; j++) {

        //Output sparse array
        System.out.println("Sparse array");

        for (int i = 0; i < array2.length; i++) {
        //1. Read the value of 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++) {

        //3. Printing
        System.out.println("Output restored array");
        for (int[] ints : array3) {
            for (int anInt : ints) {


Keywords: Java Back-end

Added by horsetags on Wed, 12 Jan 2022 10:17:32 +0200