Arrays in Java

Keywords: Java less JDK Attribute

In Java, array is a kind of reference data type. It is the simplest compound data type and a collection of ordered data. Each element in the array has the same data type. You can use a uniform array name and different subscripts to determine the unique elements in the array.

According to the dimension of array, it can be divided into one-dimensional array, two-dimensional array and multi-dimensional array.

1, Definition of array

There are two syntax for defining arrays in Java:

type arrayName[];
type[] arrayName;
  • Type is any data type in Java, including basic type and reference type; note here: to declare an array is to tell the computer what the data type in the array is;
  • arrayName is an array name, which must be a legal identifier;
  • [] indicates that the variable is an array type variable.

There is no difference between the two forms, and the effect is exactly the same.

Different from C and C + +, when Java defines an array, it only gets a variable to hold the array, and does not allocate memory space for array elements, so it cannot be used.

The number of array elements (i.e. array length) cannot be specified in []. If it is specified, an error will be reported. In this way, memory space cannot be allocated for array elements.

int score[10]; // error

It is important to remember that you must allocate memory space for the array so that each element of the array has a space to store.

To allocate memory space, you need to use the new operator:

int[] arr; // Define an int array variable arr
arr = new int[3]; // Specify the number of array elements as 3 for the int array variable arr, that is, allocate memory space

Or:

int[] arr = new int[3]; // This is equivalent to allocating memory space for int array variables when they are defined.

Note here that in Java, once an array is created, the size of its storage space cannot be changed.

2, Initialization of arrays

After allocating memory for an array, you also need to assign an initial value to the array, that is, initialization.

In fact, no matter how to initialize the array, as long as memory space is allocated for the array elements, the array elements have initial values. The initial value can be obtained in two forms: one is automatically assigned by the system, and the other is specified by the programmer.

In Java, there are three ways to initialize arrays.

1. Dynamic initialization

float floatArray[] = new float[3];
floatArray[0] = 1.0f;
floatArray[1] = 132.63f;
floatArray[2] = 100F;

Use the new operator to create the array, and specify the size of the array at the time of creation. After the array is created, the value of the element is uncertain. You need to assign a value to each array element, and its subscript starts from 0.

Note: do not specify the length of the array and assign the initial value to each array element when initializing the array, which will result in an error.

float floatArray[3] = new float[3]; // error

2. Static initialization

When you declare an array, you allocate memory and initialize the array elements. This is called static initialization.

int intArray[] = {1, 2, 3, 4};
String stringArray[] = {"Java", "OOP", "Array"}; 

When using this method, the declaration and initialization of the array should be synchronized. This is the error as follows:

int intArray[];
intArray = {1, 2, 3, 4}; // error

3. Default initialization

Use the new keyword to create an array and assign values to the elements in the array to complete the initialization operation.

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

Here, new does not need to specify the length of the array. The length of the array is determined by the subsequent initialization operation, which is the default.

3, Multidimensional array

1. Two dimensional array

In Java, two-dimensional array is regarded as array, that is, two-dimensional array is a special one-dimensional array, and each element is a one-dimensional array.

There are three ways to initialize a 2D array.

int[][] temp1 = new int[][]{{1, 2}, {3, 4}}; // Initialize at definition time
int[][] temp2 = new int[2][2]; // Given space, reassign
int[][] temp3 = new int[2][]; // The second dimension of the array is empty and changeable

Let's take a look at a few examples of manipulating a two-dimensional array.

Get single element

public class Main {
  public static void main(String[] args) {
    double[][] class_score = {{10.0, 99, 99}, {100, 98, 97}, {100, 100, 99.5}, {99.5, 99, 98.5}};
    System.out.println("The value of the second column element in the second row:" + class_score[1][1]);
    System.out.println("Value of element in the third column of the fourth row:" + class_score[3][2]);
  }
}

Get whole line elements

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    double[][] class_score = {{100, 99, 99}, {100, 98, 97}, {100, 100, 99.5}, {99.5, 99, 98.5}};
    Scanner scan = new Scanner(System.in);
    System.out.println("The current array has only" + class_score.length + "Line, which line of elements would you like to see? Please input:");
    int number = scan.nextInt();
    for (int i = 0; i < class_score[number - 1].length; i++) {
      System.out.println("The first" + number + "Row number[" + i + "]The values of the elements are:" + class_score[number - 1][i]);
    }
  }
}

Get entire column elements

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    double[][] class_score = {{100, 99, 99}, {100, 98, 97}, {100, 100, 99.5}, {99.5, 99, 98.5}};
    Scanner scan = new Scanner(System.in);
    System.out.println("Which column value do you want to get? Please input:");
    int number = scan.nextInt();
    for (int i = 0; i < class_score.length; i++) {
      System.out.println("The first " + (i + 1) + " Row number[" + number + "]The values of the elements are" + class_score[i][number-1]);
    }
  }
}

Get all elements

public class Main {
  public static void main(String[] args) {
    double[][] class_score = {{100, 99, 99}, {100, 98, 97}, {100, 100, 99.5}, {99.5, 99, 98.5}};
    for (int i = 0; i < class_score.length; i++) { // Traverse row
      for (int j = 0; j < class_score[i].length; j++) {
        System.out.println("class_score[" + i + "][" + j + "]=" + class_score[i][j]);
      }
    }
  }
}

2. More dimensional arrays

The declaration, initialization and use of multidimensional array are similar to 2D array. Taking 3D array as an example, 3D array can be understood as a one-dimensional array, and each element of its content is a two-dimensional array. By analogy, you can get an array of any dimension.

3, Arrays utility class

Arrays class is a tool class provided by JDK for manipulating arrays. It contains many methods of array operation, which is located in the java.util package. This arrays class is all static decorated methods, so it can be called directly through the class name.

Here are some common methods of Arrays class.

1. Array comparison

The condition of array equality not only requires that the number of array elements must be equal, but also the elements of corresponding positions. The Arrays class provides the equals() method to compare the entire array.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    String[] str1 = {"1", "2", "3"};
    String[] str2 = {"1", "2", new String("3")};
    System.out.println(Arrays.equals(str1, str2)); // true
  }
}

2. Array conversion string

public class Main {
  public static void main(String[] args) {
    int[] a = {1, 2, 3};
    System.out.println(a); // Printed out is the hashcode
    System.out.println(Arrays.toString(a)); // Printed out is an array [1, 2, 3]
  }
}

3. Sorting of arrays

The sort() method in the Arrays class can ascending Arrays:

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] score = {79, 65, 93, 64, 88};
    Arrays.sort(score);
    String str = Arrays.toString(score);
    System.out.println(str); // [64, 65, 79, 88, 93]
  }
}

What if you want to sort in descending order? There are two ways.

Using the Collections.reverseOrder() method:

import java.util.Arrays;
import java.util.Collections;

public class Main {
  public static void main(String[] args) {
    Integer[] score = {79, 65, 93, 64, 88};
    Arrays.sort(score, Collections.reverseOrder());
    String str = Arrays.toString(score);
    System.out.println(str); // [93, 88, 79, 65, 64]
  }
}

To implement the replication compare() method of the Comparator interface:

import java.util.Comparator;

class MyComparator implements Comparator<Integer> {
  @Override
  public int compare(Integer o1, Integer o2) {
    return o2 - o1;
  }
}


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    Integer[] score = {79, 65, 93, 64, 88};
    Arrays.sort(score, new MyComparator());
    String str = Arrays.toString(score);
    System.out.println(str); // [93, 88, 79, 65, 64]
  }
}

Note: when using the above two methods, the array must be of wrapper type, otherwise it will fail to compile.

4. Array padding

The Arrays class provides a fill() method, which can be used for numerical filling at a specified location. Although the fill() method can fill the array, its function is limited. It can only replace all elements in the array with one value.

public class Main {
  public static void main(String[] args) {
    int[] num = {1, 2, 3};
    Arrays.fill(num, 6);
    System.out.println(Arrays.toString(num)); // [6, 6, 6]
  }
}

5. Find element

You can use the binarySearch() method of the Arrays class to find the array, which returns the index value of the element to be searched.

public class Main {
  public static void main(String[] args) {
    char[] a = {'a', 'b', 'c', 'd', 'e'};
    int i = Arrays.binarySearch(a, 'd');
    System.out.println(i); // 3

    char[] b = {'e', 'a', 'c', 'b', 'd'};
    Arrays.sort(b);
    int j = Arrays.binarySearch(b, 'e');
    System.out.println(j); // 4
  }
}

6. Copy of array

There are four ways to copy arrays in Java:

  • copyOf() method of Arrays class

  • copyOfRange() method of Arrays class

  • arraycopy() method of System class

  • clone() method of Object class

1) The copyOf() method starts from the first element of the array and copies to the specified length.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] scores = new int[]{57, 81, 68, 75, 91};
    System.out.println(Arrays.toString(scores)); // [57, 81, 68, 75, 91]

    int[] newScores = Arrays.copyOf(scores, 5);
    System.out.println(Arrays.toString(newScores)); // [57, 81, 68, 75, 91]

    System.out.println(scores == newScores); // false
    System.out.println(Arrays.equals(scores, newScores)); // true
  }
}

At the same time of copying, you can also increase the memory space of the new array for later use:

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] scores = new int[]{57, 81, 68, 75, 91};
    int[] newScores = (int[])Arrays.copyOf(scores,8);
    System.out.println(Arrays.toString(newScores)); // [57, 81, 68, 75, 91, 0, 0, 0]
    newScores[5] = 100;
    newScores[6] = 200;
    newScores[7] = 300;
    System.out.println(Arrays.toString(newScores)); // [57, 81, 68, 75, 91, 100, 200, 300]
  }
}

2) , copyOfRange() method copies the specified length of the specified array to a new array.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] scores = new int[] { 57, 81, 68, 75, 91, 66, 75, 84 };
    int[] newScores = (int[]) Arrays.copyOfRange(scores, 0, 5);

    System.out.println(scores == newScores); // false
    System.out.println(Arrays.toString(newScores)); // [57, 81, 68, 75, 91]
  }
}

3) , arraycopy() method

The arraycopy() method is located in the java.lang.System class. The syntax is as follows:

System.arraycopy(dataType[] srcArray,int srcIndex,int destArray,int destIndex,int length)
  • srcArray represents the original array;

  • srcIndex represents the starting index in the original array;

  • destArray represents the target array;

  • destIndex indicates the starting index in the target array;

  • Length indicates the length of the array to copy.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    // Original array, length 8
    int[] scores = new int[]{100, 81, 68, 75, 91, 66, 75, 100};

    // target array
    int[] newScores = new int[]{80, 82, 71, 92, 68, 71, 87, 88, 81, 79, 90, 77};

    System.arraycopy(scores, 0, newScores, 2, 8);
    System.out.println(scores == newScores); // false
    System.out.println(Arrays.toString(newScores)); // [80, 82, 100, 81, 68, 75, 91, 66, 75, 100, 90, 77]
  }
}

Equivalent to replacing some elements in the target array.

Note: when using this method to copy an array, the length+srcIndex must be less than or equal to srcArray.length, and the length+destIndex must be less than or equal to destArray.length.

4) , clone() method

The clone() method can also replicate arrays. This method is a method in the class Object, which can create an Object with a separate memory space. Because an array is also an Object class, you can also use the clone() method of the array Object to copy the array.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] scores = new int[]{100, 81, 68, 75, 91, 66, 75, 100};

    int[] newScores = scores.clone();

    System.out.println(scores == newScores); // false
    System.out.println(Arrays.toString(newScores)); // [100, 81, 68, 75, 91, 66, 75, 100]
  }
}

4, Deep and shallow copies of arrays

Special attention should be paid here: in fact, the array copying methods mentioned above are all shallow copies, which can normally meet the requirements for elements of basic type or String type, but are not suitable for reference types.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    Dog[] dogs = new Dog[]{new Dog("da-huang", 1), new Dog("da-hui", 2)};
    Dog[] newDogs = Arrays.copyOf(dogs, 2);

    System.out.println(dogs == newDogs); // false

    System.out.println(dogs[0].name); // da-huang

    newDogs[0].name = "xiao-huang";
    System.out.println(newDogs[0].name); // xiao-huang
    System.out.println(dogs[0].name); // xiao-huang
  }
}

public class Dog {
  String name;
  int age;

  Dog(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

Shallow copy only copies the reference address of the object. Two objects point to the same memory address, so if you modify any of them, the other value will change accordingly.

The deep copy is to copy the object and its value. If two objects modify any value, the other value will not change. Therefore, the principle of deep copy is to make the reference type attribute of the original object and the copied object not point to the same block of heap memory, which provides a separate memory space for the new object.

We only need to complete the deep copy of the object, and the deep copy of the array will be easy to do.

The depth of objects in Java can be seen here: https://togoblog.cn/categories/Java/java-copy-object

5, Traversal of array

1. for loop

public class Main {
  public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};

    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
  }
}

2. foreach cycle

public class Main {
  public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};

    for (int value : arr) {
      System.out.println(value);
    }
  }
}
Published 12 original articles, praised 0, visited 16
Private letter follow

Posted by Ruiser on Fri, 14 Feb 2020 03:23:36 -0800