javaEE_day04 ☞ java array learning and sorting

Understanding arrays

An array is also a data type, which is itself a reference type.
1. what is an array: a container that stores the same data type

2. features:

Java arrays can store both basic type data and reference type data, as long as all array elements have the same type;
Ordered (subscript, starting from 0);
Once the initialization of the array is completed, the space occupied by the array in memory will be fixed, so the length of the array will not be changed. (attribute length) even if the data of an array element is cleared, the space occupied by it is still reserved and belongs to the array. The length of the array remains unchanged.

Define array

Array name of type [] of data element;
int[] nums;
int nums[];

Array is a variable of reference type. Therefore, when defining a variable with it, it only means that a reference variable (that is, a pointer) has been defined. This reference variable has not pointed to any valid memory. Therefore, the length of the array cannot be specified when defining an array. Moreover, since the definition of array only defines a reference variable and does not point to any valid memory space, there is no memory space to store array elements. Therefore, this array cannot be used. It can only be used after the initialization of the array.

Create array (request memory)

As long as memory space is allocated for the array elements, the array elements have initial values.
There are two ways to initialize an array.

Static initialization: during initialization, the programmer explicitly specifies the initial value of each array element, and the system determines the array length.
Dynamic initialization: during initialization, the programmer only specifies the array length, and the system allocates the initial value for the array elements.

1. static initialization
The syntax format of static initialization is as follows:

arrayName = new type[] {el ementl, element2 , element3 , element4 .. . } 

In addition, static initialization has the following simplified syntax format:

type[] arrayName = {elementl, element2, element3, element4 . . . } 

2. dynamic initialization
The syntax format of dynamic initialization is as follows:

arrayName = new type[length] ;

After array initialization, you can use the array, including assigning values to array elements, accessing array element values, and obtaining array lengths.

Store data

// Assign a value to the first array element of nums 

Use array

// Output the first element of the num array

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

Enhanced for loop (foreach loop)

for(int i : nums){

//Array becomes string

        int nums[];
		nums=new int[10];
		//Array becomes string
		System.out.println(Arrays.toString(nums));    //[1, 0, 0, 0, 0, 0, 0, 0, 0, 2]
		for(int i=0;i<nums.length;i++) {
			//Assign values to elements in an array
			System.out.println(nums[i]);    //The result is 10 90
		//Test whether the elements in the array are really assigned
		System.out.println("aaa"+nums[2]);    //aaa90, so this method can assign values to array elements
		for(int n:nums) {
			System.out.println(n);   //The result is 10 80
		System.out.println("Not assigned"+nums[2]);   //Not assigned 0

From the above program, when using foreach to iterate to access array elements, the circular variable in foreach is equivalent to a temporary variable, and the system will assign array elements to this temporary variable in turn. This temporary variable is not an array element, but only saves the values of array elements. Therefore, you cannot use this foreach loop if you want to change the value of an array element.

Use of args array of main method

public static void main(String[] args) {
		//Exercise: sum array elements
		int sum=0;
		for(int i=0;i<args.length;i++) {
			int n=Integer.parseInt(args[i]);
			System. out .println(n+" ");
		System. out .println("The sum is:"+sum);
		//System. out .println(Arrays.toString(args)); 

give the result as follows

Sum: 10

Copy and expansion of array

Arrays ToString (type[] a): this method converts an array into a string

        int [] a= {1,2,3,4,5};
		int [] b= new int[10];
		//Copy of array
		//b= {1,2,3,0,0......};
	    //First parameter: original array
		//Second parameter: the starting position of the original array element
		//Third parameter: target array
	    //Fourth parameter: the starting position of the target array element
		//Fifth parameter: length
	//	System.arraycopy(a, 0, b, 0, 3);
	//	System.out.println(Arrays.toString(b));
		//Exercise: b={0,0,3,4,0...}
		System.arraycopy(a, 2, b, 2, 2);

Array expansion (a new array is actually created). See the following figure for details

        //Array expansion (a new array is actually created)
		//First parameter: original array (copy)
		//Second parameter: length after capacity expansion
		String[] names= {"wolf"};
		names[1]= "Lisi";
		// The index value specified by the access array element is equal to the array length, so the following code will cause an exception at run time 

If the index value specified when accessing an array element is less than 0, or greater than or equal to the length of the array, the compiler will not make any errors, but an exception occurs at runtime: java Lang.arrayindexoutotboundsexception: n (array index out of bounds exception),

       names=Arrays.copyOf(names, names.length+1);
       //The result is [Zhang San, Li Si]

Memory: heap, stack, method area, local method stack, register
Stack local variable
Stacking objects
Thread garbage collection of jvm

Why is there stack memory and heap memory?
When a method is executed, each method will create its own memory stack, and the variables defined in this method will be put into this memory stack one by one. With the end of the method execution, the memory stack of this method will be destroyed naturally. Therefore, all local variables defined in the method are placed in stack memory; When an object is created in a program, it will be saved to the runtime data area for reuse. This runtime data is heap memory. The object in heap memory will not be destroyed with the end of the method. Even if the object may be referenced by another reference variable after the end of the method, the object will not be destroyed. Only when an object does not have any reference variables to reference it, the system's garbage collector will collect it at the appropriate time.

Tip: when looking at an array, you must regard the array as two parts: one part is array reference, that is, array reference variables defined in the code; The other part is the actual array object. This part is run in the heap memory. Usually, it cannot be accessed directly, but only through the array reference variable.

Sorting of array elements

1. bubble sort
Compare the two, the big one sinks, the small one floats, from small to large

Picture from here.

Example: sort 23, 56, 22, 15
First round sorting:
The results were 23, 22, 15, 56. Exchanged 3 times
The process is as follows


Second round sorting:
The results are 22, 15, 23, exchanged twice
The process is as follows


Third round sorting:
The results were 15, 22. Exchanged once

Implemented in Java code:

		int[] num= {23,56,22,15};
		int x;
        //Three rounds of sorting
		for(int i=0;i<3;i++) {
		    //Exchange times
			for(int j=0;j<num.length-1-i;j++) {
				if(num[j]>num[j+1]) {
		//The result is [15, 22, 23, 56]

2. Select Sorting:

Implemented in Java code:

        for(int i=0;i<num.length-1;i++) {
			for(int j=i+1;j<num.length;j++) {
				if(num[i]<num[j]) {
					int x=num[i];

In addition to the above, the sorting method is arrays Sort (Num); You can also sort.

Two dimensional array

1. statement:
int[][] arrays;
//The first [] represents a row and the second represents a column
int[] arrays[];
int arrays[][];

int[] a[],b;   //a two-dimensional, b one-dimensional Both exclude
int[] c=new int[2];
int [][] d=new int[2][3];
//Only the same data type can be assigned

a=c;    //Two dimensional array assigned to one dimensional array error
b=c;    //ok
a=d;    //error, because a just declares that d points to memory
                     b=d;    //error   ??????
a[0]=c;  //A is two-dimensional, but a[0] represents the first row and is a one-dimensional array
a[0]=d;  //error

2. create:
Arrays=new int[2][3]// 2 rows and 3 columns

3. assignment:
The result is:

0 0 1
0 0 0

Get array elements, using nested loops

//2D array name length is the row of a two-dimensional array
		int[][] nums;
		nums=new int[2][3];
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){

The result is:

0	0	0	
0	1	0

Other ways to define 2D arrays:

//Other ways to define 2D arrays
		int[][] nums=new int[2][3];
		int[][] nums2= {{1,2,3},{4,5,6}};
		int[][] nums3=new int[][]{{1,2,3},{4,5,6}};

Definition of irregular two-dimensional array

        //int[][] nums=new int[][3];    error
		//int[][] nums=new int[][];   error
		int[][] nums=new int[3][]; //3 lines
		nums[0]=new int[3];
		nums[1]=new int[1];
		nums[2]=new int[5];
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){

The result is:

0	0	0	
0	0	0	0	0	


    //Sum of diagonal lines
	public static void test() {
		int[][] nums=new int[][]{{1,2,3},{1,2,2},{3,2,2}};
		int sum=0;
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){
		    	if(i==j||i+j==2) {
	//Matrix transpose
	 * [0][0]  [1][0]
	public static void test4() {
		int[][] nums=new int[][]{{1,2,3},{4,5,6}};
		int[][] nums2=new int[3][2];
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[0].length;j++){
		for(int i=0;i<nums2.length;i++){
		    for(int j=0;j<nums2[i].length;j++){
	//Yanghui triangle
	public static void test3() {
		Scanner sc=new Scanner(;
		System.out.println("input n:");
		int n =sc.nextInt();
		int[][] nums = new int[n][];
		for(int i=0;i<nums.length;i++){
			nums[i]=new int[i+1];
		    for(int j=0;j<nums[i].length;j++){
		    	if(j==0||i==j) {
		    	}else {
		for(int i=0;i<nums.length;i++){
		    for(int j=0;j<nums[i].length;j++){

Tags: Java

Posted by freeloader on Mon, 30 May 2022 09:11:50 +0530