Java array

Array introduction

  • An array is a combination of multiple data of the same type to achieve unified management of these data
  • An array is a reference type. Array data is an Object.
  • The elements in an array can be any data type, including primitive and reference types
  • The array type is single and can only hold the same type of data
  • Once an array is created, its size is fixed
  • Each element in the array has its own position (subscript), starting at 0

So arrays are usually used to store data of a fixed size: class grades, for example

int scores = {100.90.98.99.88.80}
Copy the code

Create an array

Key array keywords :[]

Int [] a is the same as int a[].

2.1 Only declare without assigning

type [] var;或者 type var [] ;

Such as:

int score[];
int [] score;
Object [] obj;  //Object is the ancestor of Java syntax
Copy the code

2.2 Declare and assign

type [] var = new type[size]; // Create data, array elements are empty. Value defaults to the default value for that type

type [] var = {elm,elem2,elem3,… } // The data is assigned at the same time

public static void main(String[] args) {

    // declare the default value
    int score[] = new int[9];
    for(int i = 0; i<score.length; i++) { System.out.print(score[i]+"\t");
    }

    System.out.println("-- -- -- -- -- -- -- -- -- -- -- --");
    // Create and assign
    int score2[] = {100.90.88.85.66};
    for(int i = 0; i<score2.length; i++) { System.out.print(score2[i]+"\t");
    }
Copy the code

2.3 New Array memory model

New: a Java keyword used to create new memory space to create new objects

2.4 Subscript operation elements

2.4.1 Assigning values to elements by subscript

int score[] = new int[9];

// Specify element assignment
score[2] = 10;
score[5] = 50;
Copy the code

2.4.2 Obtaining element content by subscript

int num2 = score[2];
System.out.println("num2="+num2);

for(int i = 0; i<score.length; i++) { System.out.print(score[i]+"\t");
}
Copy the code

2.5 Precautions

  • Java uses the keyword new to create array objects
  • Each element in the array can be referenced only after it is defined and allocated space by the operator new.
  • Array element references: array name [array element subscript]
    • The subscripts of array elements can be integer constants or integer expressions. For example, a[3], B [I], C [6* I];
    • Array element indices start at 0; Valid subscripts for an array of length N range from 0 to n-1. Such as 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 that specifies its length. For example, a.length specifies the length of array A (number of elements).

Three, go through the number group

Groups of iterated numbers can be traversed by subscript or enhanced foreach loops

3.1 Ordinary for loops

Since we can access elements using arr[index], we can loop through arr. Length to get the values of different indexes;

But note: the index range is :0-(length-1), cannot be greater than or equal to length because the subscript is evaluated from 0. Otherwise throw an out-of-bounds array exception

int score[] = {100.90.88.85.66};
for(int i = 0; i<score.length; i++) { System.out.println(score2[i]); }Copy the code

This is to iterate over all the elements in the Score array and print them out

3.2 Enhance the for loop

Java has a powerful loop structure that can be used to process each element in an array in turn without the distraction of specifying subscript values. The statement format for this enhanced for loop is:

for(variable : arr)statement

Such as:

int score[] = {100.90.88.85.66};
for(int ele:score){
    System.out.println(ele);
}
Copy the code

This syntax achieves the same effect as the ordinary for loop above. This for each loop is much cleaner and less error-prone

Array copy

If you want to copy all the values of an array into a new array, you use the copyOf method of the Arrays class:

The second argument is the length of the new array. This method is usually used to increase the size of an array

int score[] = {100.90.88.85.66};

// The length of the part that exceeds the original data: use default 0 instead
int[] newArr01 = Arrays.copyOf(score, 10);

// If the length is insufficient, take the corresponding data from front to back
int[] newArr02 = Arrays.copyOf(score, 3);

System.out.println("Original array =" + Arrays.toString(score));
System.out.println("New array 1 =" + Arrays.toString(newArr01));
System.out.println("New array 2 =" + Arrays.toString(newArr02));
Copy the code

Matters needing attention:

  • If the array elements are numeric, the extra elements are assigned a value of 0;
  • If the array element is Boolean, the value is assigned to false.
  • Conversely, if the length is less than the length of the original array, only the uppermost data element is copied.

5, array sort

5.1 Arrays Tool class sorting

Java.util. Arrays: Belongs to a utility class, so you need to lead packages before using them

public static void main(String[] args) {
    int score [] = {99.89.78.88.69.70};
    String ch[] = {"B"."C"."A"."F"."D"};
    System.out.println("Before sorting :");
    for (int i = 0; i < ch.length; i++) {
        System.out.print(ch[i]+"\t");
    }
    System.out.println();

    // Sort
    //1. Provides only ascending sort from smallest to largest, but does not provide descending sort. Do it yourself
    //2. Also called natural order. A(65) B(66) C(67) D(68)
    Arrays.sort(ch);

    System.out.println("After sorting :");
    for (int i = 0; i < ch.length; i++) {
        System.out.print(ch[i]+"\t"); }}Copy the code

4.2 Sorting through Algorithms (Bubbling)

Take ascending order as an example:

  1. You take two adjacent numbers, you compare them, you move the big numbers back. Cycle through the comparison to find the largest number
  2. Since only one data can be determined per loop, multiple nested loops are required to complete the final sort
  3. Details are shown below.

public static void main(String[] args) {

    int score [] = {99.89.78.88.69.70};
    / / I = 0 {89,78,88,69,70,99};
    78,88,69,70,89,99 / / I = {1};
    78,69,70,88,89,99 / / I = {2};

    System.out.println("The original result :");
    for (int j = 0; j < score.length; j++) {
        System.out.print(score[j]+"\t");
    }
    System.out.println();

    // Sort: sort the first several times, and the last one automatically determines the position. Sort less once
    // Select the largest one at a time
    for (int i = 0; i < score.length-1; i++) {

        // Compare the two adjacent ones and move the larger one back
        for (int j = 0; j < score.length-1-i; j++) {
            // If the front is larger than the back, change the position
            if(score[j]>score[j+1]) {
                // Pairwise swap through temporary variables
                int temp = score[j];
                score[j] = score[j+1];
                score[j+1] = temp;
            }

        }
        System.out.println("The first"+(i+1) +"Results of this execution :");
        for (int j = 0; j < score.length; j++) {
            System.out.print(score[j]+"\t"); } System.out.println(); }}Copy the code