Java to improve the array of articles (1)

 

table of Contents

Why is the (zero) array special?

(1) Array overview

(2) One-dimensional array

(Three) two-dimensional array

Understand the array model of each dimension in JAVA


Recently I learned the knowledge of JAVA arrays and wrote a blog as study notes for easy reference, mainly from four aspects. (0) Why is the array special? (1) Introduction to array (2) One-dimensional array, definition, declaration, initialization, use, memory analysis, (3) Two-dimensional array, definition, declaration, initialization, use, memory analysis. (4) When using the array class and its methods, add, delete, modify and check. Arrays are related to sorting algorithms, such as bubble sorting, least dichotomy, etc., which are introduced in Data Structures and Algorithms. The application of arrays here only introduces the addition, deletion, modification, and checking of data in the array.

Why is the (zero) array special?

There are a lot of other ways to hold objects in JAVA, so what makes arrays unique?

There are three differences between arrays and other types of containers: efficiency, types, and the ability to store basic types . In Java, arrays are the most efficient way to store and randomly access sequences of objects. Arrays are simple linear sequences. , Which makes element access very fast, but the price paid for this speed is that the size of the array object is fixed and its life cycle is immutable. The reason why arrays are better than containers like generics is that you can create an array to hold a specific type, which means that you can check by the compiler to prevent inserting error messages and extracting improper types.

So, why define an array?

Define 100 integer variables, the structure is as follows:

int i1, i2, i3, ... i100;

 

This way of definition is very troublesome, because these variables are not related to each other. When you want to output the contents of these 100 variables, it means that you have to write System.out.println()statements 100or print 100 times with a for loop.

In fact, an array refers to a set of variables of related types, and these variables can be operated in a uniform way, that is, a set of the same data type. In this way, data is saved to realize data addition, deletion, modification, and check. The array itself is a reference data type.

(1) Array overview

Array (Array) is a collection of multiple data of the same type arranged in a certain order, named with a name, and unified management of these data by numbering. Commonly used concepts in arrays include array name, subscript, element, and array length.

  • The array itself is a reference data type, and the elements in the array can be any data type, including basic data types and reference data types.
  •  Creating an array object will open up a whole continuous space in the memory, and the array name refers to the first address of this continuous space.
  •  Once the length of the array is determined, it cannot be modified.
  •  We can directly call the element at the specified position by subscript (or index), which is very fast.
  •  Classification of arrays: According to the dimensions: one-dimensional array, two-dimensional array, three-dimensional array,...; according to the data type of the element: an array of basic data type elements, an array of reference data type elements (ie, an array of objects)

There are two ways to declare an array, static initialization and static initialization

Static initialization of the array:

  • Data type [] Array name =  new data type [] {element 1, element 2, element 3,...}; such as int [] sa=new int[]{1,2.3};

Array dynamic initialization:

  • Declare and open up an array:
    • Data type [] Array name =  new data type [length]; such as int [] a=new int[5];
    • Data type Array name [] =  new data type [length]; such as int a[]=new int[4];

Then when the array opens up space, you can use the following operations:

  • The access of the array is completed by index, that is: "array name [index]", such as a[2]; the index of the array 0starts from the beginning, and the range of the index is 0 ~ array length - 1, for example 3, an array of space is opened , so it can be used The index is: 0,1,2, if the access exceeds the index range of the array at this time, an java.lang.ArrayIndexOutOfBoundsException exception message will be generated ;
  • When our array uses dynamic initialization to open up space, each element in the array is the default value of the corresponding data type of the array; and each data type has its own default value.
  • The array itself is an ordered set operation, so the operation of the contents of the array is often done in a loop mode. The array is a limited data set, so for loops should be used  .
  • In  Java there is provided a dynamic array length achieved by: the array name .length
public class ArrayDemo {
	public static void main(String args[]) {
		int data[] = new int[3]; /*开辟了一个长度为3的数组*/
		data[0] = 10; // 第一个元素
		data[1] = 20; // 第二个元素
		data[2] = 30; // 第三个元素
		for(int x = 0; x < data.length; x++) {
			System.out.println(data[x]); //通过循环控制索引
		}
	}
}
/*
输出结果为
10
20
30

*/

 

(2) One-dimensional array

    A one-dimensional array is a collection of data composed of the same data type. It is composed of one-dimensional data, as shown in the figure below:

(1) Statement

       There are two ways to declare a one-dimensional array: type var[] or type[] var, for example int a[]; or int []a;

(2) Initialization

There are two initialization methods, dynamic initialization and static initialization.

  • Dynamic initialization: the operation of array declaration and allocating space for array elements and assignment are carried out separately

  • Static initialization: When defining the array, allocate space and assign values ​​to the array elements.

(3) Reference

  • After defining and using the operator new to allocate space for it, each element in the array can be referenced;
  • Reference method of array elements: array name [array element subscript]
  •  The index of an array element can be an integer constant or an integer expression. Such as a[3], b[i], c[6*i];
  • The subscript of the array element starts from 0; the valid subscript value range of an array of length n: 0 —>n-1; for example, int a[]=new int[3]; The array elements that can be referenced are a[0], a[1], a[2]
  • Each array has an attribute length indicating its length, for example: a.length indicates the length of the array a (number of elements)
  • Once the array is initialized, its length is immutable

(4) Default initialization value

The array is a reference type, and its elements are equivalent to the member variables of the class. Therefore, once space is allocated for the array, each element in it is implicitly initialized in the same way as the member variables. In the following program, the default initialization address of a[3] is 0;

public class Test {
public static void main(String argv[]){
int a[]= new int[5];
System.out.println(a[3]); //a[3]的默认值为0
}
}

Generally speaking, the default values ​​for other data types are:

(5) Memory analysis

The simplified diagram of jvm memory in Java is

 

Then, for the following program, its running process is:

 package strings;

/**
 * Created with IntelliJ IDEA.
 * User:  yongping Li
 * Date: 2020/11/14
 * Time: 15:10
 * Description: No Description
 */
public class Test{
    public static void main(String args[]){
        int[] s;
        s = new int[10];
        for ( int i=0; i<10; i++ ) {
            s[i] =2*i+1;
            System.out.println(s[i]);
        }
    }
} 

At int[] s; at s = new int[10]; at s[i] = 2*i+1;:

                         

For the following program, its memory analysis is

public class ArrayDemo {
	public static void main(String args[]) {
		int data[] = null;
		data = new int[3]; //开辟一个长度为3的数组
		int temp[] = null; //声明对象
		data[0] = 10;
		data[1] = 20;
		data[2] = 30;
		temp = data;  //int temp[] = data;
		temp[0] = 99;
		for(int i = 0; i < temp.length; i++) {
			System.out.println(data[i]);
		}
	}
}

Memory analysis:

è¿éåå¾çæè¿ °

int[] arr1 = new int[4];
arr1[0] = 10;
arr1[2] = 20;
String[] arr2 = new String[3];
arr2[1] = “刘杰”;
arr2 = new String[5];

Memory analysis:

int[] arr = new int[]{1,2,3};
String[] arr1 = new String[4];
arr1[1] = “刘德华”;
arr1[2] = “张学友”;
arr1 = new String[3];
sysout(arr1[1]);//null

Memory analysis:

 

One-dimensional array program code example:

package arrays;//: arrays/ArrayOptions.java
// Initialization & re-assignment of arrays.
import java.util.*;


public class ArrayOptions {
  public static void main(String[] args) {
    // Arrays of objects:
    BerylliumSphere[] a; // Local uninitialized variable
    BerylliumSphere[] b = new BerylliumSphere[5];
    // The references inside the array are
    // automatically initialized to null:
    System.out.println("b: " + Arrays.toString(b));
    BerylliumSphere[] c = new BerylliumSphere[4];
    for(int i = 0; i < c.length; i++)
      if(c[i] == null) // Can test for null reference
        c[i] = new BerylliumSphere();
    // Aggregate initialization:
    BerylliumSphere[] d = { new BerylliumSphere(),
      new BerylliumSphere(), new BerylliumSphere()
    };
    // Dynamic aggregate initialization:
    a = new BerylliumSphere[]{
      new BerylliumSphere(), new BerylliumSphere(),
    };
    // (Trailing comma is optional in both cases)
    System.out.println("a.length = " + a.length);
    System.out.println("b.length = " + b.length);
    System.out.println("c.length = " + c.length);
    System.out.println("d.length = " + d.length);
    a = d;
    System.out.println("a.length = " + a.length);

    // Arrays of primitives:
    int[] e; // Null reference
    int[] f = new int[5];
    // The primitives inside the array are
    // automatically initialized to zero:
    System.out.println("f: " + Arrays.toString(f));
    int[] g = new int[4];
    for(int i = 0; i < g.length; i++)
      g[i] = i*i;
    int[] h = { 11, 47, 93 };
    // Compile error: variable e not initialized:
    //!print("e.length = " + e.length);
    System.out.println("f.length = " + f.length);
    System.out.println("g.length = " + g.length);
    System.out.println("h.length = " + h.length);
    e = h;
    System.out.println("e.length = " + e.length);
    e = new int[]{ 1, 2 };
    System.out.println("e.length = " + e.length);
  }
} /* Output:
b: [null, null, null, null, null]
a.length = 2
b.length = 5
c.length = 4
d.length = 3
a.length = 3
f: [0, 0, 0, 0, 0]
f.length = 5
g.length = 4
h.length = 3
e.length = 3
e.length = 2
*///:~

The results of the operation are:

(Three) two-dimensional array

One-dimensional array can be regarded as a row of data; as shown in the figure below:

The two-dimensional array can be regarded as a list, as shown below:

Therefore, a two-dimensional array can be regarded as a combination of two one-dimensional arrays.

(1) Declaration and initialization

 

Initialization of a two-dimensional array:

  • Dynamic initialization of the array: data type object array [][] = new data type [number of rows][number of columns];
  • Static initialization of array: data type object array [][] = new data type [number of rows][number of columns]{ {value, value,…}, {value, value,…},…};

(2) Memory analysis

 

 

Understand the array model of each dimension in JAVA

 

 

Guess you like

Origin blog.csdn.net/weixin_41792162/article/details/109692597