All day long, all you want to know about Java arrays is here!

Hello everyone, I'm KookNut39 and Tommy. I was Tommy when writing articles and Java at CSDN. I share some things I think are more important in the learning process. I'm committed to helping beginners get started. I hope it can help you make progress. Interested bloggers are welcome to follow and learn java knowledge with bloggers. You can also check the previous articles in the column. I hope you can discuss technology with you in the future.

1. What is an array

Array is a linear data structure. Linear structure is continuous in memory and is a collection used to store the same type of data

Array features: continuous, each element has a subscript, which can be searched quickly, but adding and deleting from the middle is more troublesome

The array itself is a reference data type, that is, an object. However, arrays can store both basic data types and reference data types.

2. Array declaration

When declaring an array variable, you need to give the array type (the data type stored in the array must be the same as that of the array) and the name of the array variable.

//The first way to declare 
//Array type [] array variable name;
int[] a;
//The second way to declare
//Array type array variable name [];
int a[];

be careful:

There is no difference between the two declaration methods in the Java language, but most Java programmers prefer the first declaration style because it separates array types from variable names.

3. Creation of array

The above statement only declares variable a and does not initialize a as a real array. You should use the new operator to create an array.

  1. While declaring the array, allocate memory according to the specified length, but the element values in the array are the default initialization values (int type is 0, String type is null, Boolean type is false).
  int [] a = new int [10];

An array that can store 10 integers is created. When using this method to create an array, the value in the square bracket to the right of the equal sign is the amount of data stored in the array. The square bracket does not need to be a constant.

The subscript of the declared array is 0 ~ 9, not 1 ~ 10. The subscript of the array starts from 0.

After the array is created, you can assign values to the array elements.

You can use a loop:

int [] a = new int [10];
for ( int i = 0;i<10; i++){    
    a[i] = i; //Assign i to the element with subscript i
}

Elements before executing the for loop:

Elements after executing the for loop:

be careful:
When cycling, you must pay attention to the number of cycles. If I in a[i] exceeds 0 ~ 9, an error will be reported

When the above error prompt appears, check whether the array index is out of bounds.

Sometimes when we don't know the length of the array (array length is a variable), we can use a.length to obtain the array length in order to prevent the index from crossing the boundary.


Since the array subscript starts from 0, the maximum value of i during the loop should be a.length-1.

  1. Declare an array, allocate memory, and initialize it
int [] a = new int[]{1, 2, 3, 4, 5};
  1. It is the same as the former, except that the syntax is relatively simple
   int[] a = {1, 2, 3, 4, 5};

In Java, the length of array is allowed to be 0. In special cases, the length of 0 can provide convenience for us.

be careful:

  1. Once you create an array, you cannot change its size. If you often need to expand the size of the array during operation, you should use another data structure - array list.
  2. An array length of 0 is different from null. Null means that the array is empty and does not point to any object. Special attention should be paid to the fact that some operations can be performed on the array only when the array is not null.

4. for each loop

Java has a powerful loop structure that can be used to process each element in the array in turn (other types of element collections can also be used) without being distracted by specifying the subscript value. We often call this enhanced for loop.

//Enhance the basic format of the for loop
for(The type of the array element is a temporary variable name :The name of the array){
    
     //Execute statement
    
}

Define a variable to temporarily store each element in the collection and execute the corresponding statement.

For example, output each element in array a.

Although the general for loop can achieve the same purpose, we should always pay attention to the subscript and do not cross the index.

In contrast, the for each loop statement is more concise and less error prone.

be careful:

The loop variable of the for each loop statement will traverse each element in the array without using the subscript value.

If you need to handle all the elements in a collection, the improvement of the for each loop statement on the traditional loop statement is much easier. However, in many cases, you still need to use the traditional for loop. For example, if you don't want to traverse every element in the collection, or you need to use subscript values inside the loop.

In addition to using loops to output the elements in the array, there is a simpler way to output all the values in the array, that is, using the toString method of the Arrays class. Call Arrays ToString (a) returns a string containing array elements, which are placed in parentheses and separated by commas, for example:

be careful:
Before using the Arrays class:

import java.util.Arrays;

5. Array copy

In Java, we can copy an array variable to another array variable. At this point, the two variables will reference the same array.

int [] a = {1,2,3,4,5,6};
int [] b = a;

At this time, no matter which array variable we operate on, the other will change. As follows:

When the copy is completed, the elements in the two arrays are the same:

After operating the b array, the two arrays are:

After operating array a, the changes of the two arrays are as follows:

If we want to copy all the values of an array to a new array, we need to use the copyOf method of the Arrays class. This method is usually used to increase the size of the array.

int[] b = Arrays.copyOf(a, a.length);//The second parameter in the method is the length of array b

This can also achieve the same result as the above method:

If we simply want to copy a new array without capacity expansion, we can directly use the length of the old array as the length of the new array. If you want to increase the size of the array, you can do this:

int[] b = Arrays.copyOf(a, 2*a.length);

After capacity expansion, redundant array elements will be the default initialization value corresponding to the data type.

If the length of the new array is smaller than that of the old array, only the first data element will be copied. As follows:

be careful:

Java arrays are somewhat different from C + + arrays

int [] a = new int [100]; // Java

differ

int a [100]; // C + + syntax

And equivalent to

int * a = new int [100]; // C + + syntax

Moreover, it should be noted that Java has no pointer operation and cannot get the next element of the array by adding 1 to a.

6. Array sorting

1. sort method in arrays class

To sort numeric Arrays, you can use the sort method in the Arrays class in Java

int [] a = {2,5,9,1,3,4};
Arrays.sort(a);
System.out.println(Arrays.toString(a));

As shown in the figure:

2. Bubble sorting

for (int i = 0; i < a.length-1; i++)      //Determines the number of cycles
{    
    for (int j = 0; j < a.length-i-1; j++)//Number of comparisons per cycle    
    {        
        if(a[j]>a[j+1])                   //Sort from small to large        
        {            
            int temp=a[j];            
            a[j]=a[j+1];            
            a[j+1]=temp;                  //Put the big one in the back
        }    
    }
}


Bubble sorting is to repeatedly traverse the element column and compare two adjacent elements in turn. If the latter is smaller than the previous number, exchange the two positions and repeat this action until there are no elements to exchange.

3. Select Sorting

for (int i = 0; i < a.length-1; i++)      //Determines the number of cycles
{    for (int j = i+1; j < a.length; j++) //Move index j back    
     {        
          if(a[i]>a[j])     //Compare the first number with each of the following numbers. The disadvantage is that the conditions are exchanged every time they are established{            
              int temp=a[i];            
              a[i]=a[j];            
              a[j]=temp;        
          }    
     }
}

This sort of selection requires more times to be exchanged. Compare the first element with the following elements, exchange the smaller elements once, and then exchange the first element with the following elements. There may be smaller elements behind, which have to be exchanged again. After comparing with all the elements, compare the second element with the following elements and repeat the operation, Until the comparison is finished. In the end, the operation of exchanging elements will be carried out many times to optimize this problem.

Optimized selection sorting:

for (int i = 0; i < a.length-1; i++)     //Determines the number of cycles
{    
     int minIndex = i;    
     for (int j = i+1; j < a.length; j++) //Move index j back    
     {        
              if(a[minIndex]>a[j])        //Compare the first number with each subsequent one and record the index of the smallest value 
              {            
                   minIndex=j;        
              }    
     }    
     //Swap the first value with the smallest of the following numbers    
     int temp=a[i];    
     a[i]=a[minIndex];    
     a[minIndex]=temp;
}

The optimized selection sort records the index of the smallest element in the following data, and the smallest element can be placed in the front only after one exchange.

4. Insert sort

int temp;
for (int i = 0; i < a.length - 1; i++)
{    
    temp = a[i + 1];    
    int Index = i;    
    for (;Index >= 0 && temp < a[Index];Index--)    
    {        
        a[Index + 1] = a[Index];    
    }    
    a[Index + 1] = temp;
}

Explanation: assuming that the first element is an ordered element, we extract an element that has not been ordered (the next element after the ordered element is now the second), compare the second element with the first element, and insert the second element before the first element if it is smaller than the first element, otherwise insert the element after the first element, Now there are two elements that have been sorted. Then extract an element that has not been sorted (the third one), compare this element with the sorted element one by one, insert it in front of the larger element, and then compare it with the sorted element before. Until the comparison is completed, repeat the above actions until the data in the array is sorted data.

7. Multidimensional array

Java actually has no multidimensional arrays, only one-dimensional arrays. Multidimensional arrays are interpreted as "arrays of arrays".

——Java core foundation Volume 1 (10th Edition)

But this does not affect our understanding of multidimensional arrays.

Multidimensional arrays use multiple subscripts to access array elements, which are suitable for representing tables or more complex permutations.

We mainly take two-dimensional array as an example:

1. Definitions

A two-dimensional array means that the elements in the array are also arrays,

Array of arrays - each element of a two-dimensional array is a one-dimensional array

int [][]a = {{1,2,3},{1,2,3},{1,2,3}};

2. Declaration

//The first way to declare
int [][] a;//This is recommended to separate array types from variable names
//The second way to declare
int a[][];

This is just a declaration and cannot be used without initialization

3. Create / initialize

Array creation

//An integer two-dimensional array is defined. The two-dimensional array has three one-dimensional arrays. Each one-dimensional array contains three elements, and each element is assigned a value
int [][]a = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
//Abbreviation
int [][] b  = {{1,2,3},{4,5,6},{7,8,9}};
//An integer two-dimensional array is defined. This two-dimensional array has three one-dimensional arrays, and each one-dimensional array contains five elements Each element has no assignment
int [][] c = new int[3][5];

After the array is initialized, each element can be accessed using two square brackets. For example, b[1] [2] represents the element with index 2 in the one-dimensional array with index 1 in the two-dimensional array b, that is, 6.

4. Iteration

The for each loop statement cannot automatically process each element of a two-dimensional array. It is processed according to rows, that is, one-dimensional array. To access all elements of two-dimensional array a, you need to use two nested loops.

//for loop statement
int [][] a = new int [][]{{1,2},{3,4}};
for(int i =0;i<a.length;i++){//Loop external array i=0, inner loop {1,2} I = 1 to {3,4}
   for(int j =0;j<a[i].length;j++){  //Loop inner array  
         System.out.println(a[i][j]);
   }
}
/*
//for each Circular statement
for (int[] a1 : a) {
    for (int a2 : a1) {
         System.out.println(a2);
    }
}
*/

8. Irregular array

What is an irregular array?

Take a two-dimensional array for example. An irregular array is a two-dimensional array. The number of elements stored in a one-dimensional array is different.

For example:

int[][] a = {{1,2,3}, {4,5}};

How to use irregular arrays?

To create an irregular array, you first need a two-dimensional array that specifies the number of one-dimensional arrays.

int[][] a = new int[5][];

Then specify the size of the one-dimensional array

for (int n = 0; n < 5; n++){   
    a[n] = new int[n+1];
}

Then we can access these elements without exceeding the bounds of the index

for (int n = 0; n < a.length; n++) {    
    for (int k = 0; k < a[n].length; k++) {        
        a[n][k] = k+1;    
    }    
    System.out.println(Arrays.toString(a[n]));
}


I have summarized the knowledge about arrays. There may be some thoughtless places. You are welcome to criticize and point out in the comment area.

The code word is not easy. If you like it, give it a favor + comment + collection 🤞🤞🤞, Thank you for your support

Reference book: Java core foundation Volume 1 (10th Edition)

Keywords: Java

Added by rarebit on Wed, 19 Jan 2022 21:51:40 +0200