Introduction to JAVA_ Training from scratch_ Common reference types and API s in JAVA

Common reference types and API s in JAVA (III)

array

Definition and usage scenario of array

Definition of array: an array is a collection used to store multiple data of the same type.
Usage scenario: 1.When a large amount of storage is required**Same type of data**And these data are not required**Multiple additions and deletions**Time (understand first)

Several knowledge points of array (memory, addition, deletion, modification, length, data type)

  1. Array objects are a continuous memory space in memory

  2. Slow addition and deletion, fast modification and query

  3. The length of the array is fixed when it is created (cannot be modified).

  4. The data type stored in the array has been fixed (cannot be modified) at the time of creation.

How to create an array

Static creation (data has been written to death at the time of creation, in two ways)

1, First kind
int[] arr = {1,8,6,8,9};
2,The second kind
int[] arr2 = new int[]{9,5,4,2,3};

Dynamic creation (only specify the length when creating, and then add data, 1 way)

// Define an int array
int[] arr3 = new int[15];
// Assign values to arrays
arr3[0] = 11;
arr3[1] = 15;...

How to get data in an array

// Each element in the array has a unique index (subscript), starting from 0
int[] arr = {14,13,15,22};

/* If you need to get 15 data now, the array subscript starts from 0
	{14,13,15,22}
	 0   1  2  3
	Therefore, if you want to get the data of 15, you can use arr[2] to get it.
*/

System.out.println("To get the data of 15 in the array: " + arr[2]);

Memory model of array (nesting of memory)

 int arr[] = new int[3];
//  When the main method executes the above statement, the following operations will be performed
// 1. Create a reference arr of integer array type in stack memory
// 2. Create an object of an integer array in the heap memory, and assign the address of the object to the reference arr
// Note: when creating an array, the space in the array also has a corresponding memory address. It is understood that an array object has an address, and its elements also have addresses (and continuous memory space).

Reasons for slow addition and deletion of arrays and fast query

  1. The array uses an index. An index is associated with a data, and the memory address of the data can be calculated through the index.

  2. Every time the index is used to find data, an algorithm (the first index address + the current index * data size [uncertain]) will be used to quickly locate the memory address pointed to by the current index, so the query speed is fast.

Two ways of traversing arrays and their differences

The traversal mode of fori (traversal refers to the reference of each data, when referring to the type)

int[] arr = {5,95,1,26,51};
for (int i = 0; i < arr.length; i++){
	System.out.println(arr[i]);
}

foreach traversal mode (traversal results in a temporary local variable)

int[] arr = {5,95,1,26,51};
for(int i : arr) {
	System.out.println(i);
}

Differences between two traversal methods of fori and foreach (2)

  1. fori has an index position, while foreach has no index position
  2. Every element traversed by fori points to the memory address, and what foreach gets is a local variable that gets the data
  3. fori can modify data in a loop, but foreach cannot modify data in a loop

Adds an element at the specified index of the array

Using the method of fori loop

public class Calculate {
    public static void main(String[] args) {

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

        System.out.println("The current array value is:" + Arrays.toString(arr)); // [1, 2, 3, 4, 5]

        // Add an element at the position of array index 2: 15, then the added array should be: {1, 2, 15, 3, 4, 5}
        arr = arrAddElement(arr, 2, 15);

        // After inserting data, the value of the array is:
        System.out.println("After inserting data, the value of the array is:" + Arrays.toString(arr)); // [1, 2, 15, 3, 4, 5]
    }

    public static int[] arrAddElement(int[] arr, int index, int element) {
        // Since the length of the array cannot be changed after it is created, a new array is needed to store data. Because an element needs to be inserted, the length of the array needs to be increased by one on the basis of the original array
        int[] newArr = new int[arr.length + 1];

        // Assign the data before the index to the new array
        for (int i = 0; i < index; i++) {
            newArr[i] = arr[i];
        }

        // Assign the element to be inserted to the specified index position
        newArr[index] = element;

        // Assign the indexed data to the new array
        for (int i = index; i < arr.length; i ++) {
            newArr[i + 1] = arr[i];
        }

        // Return new array
        return newArr;
    }
}

Implemented using the System.arraycopy() method

  • Only the code of the arrAddElement() method is provided here
public static int[] arrAddElement(int[] arr, int index, int element) {
        // Since the length of the array cannot be changed after it is created, a new array is needed to store data. Because an element needs to be inserted, the length of the array needs to be increased by one on the basis of the original array
        int[] newArr = new int[arr.length + 1];

        // Assign the data before the index to the new array
        System.arraycopy(arr, 0, newArr, 0, index);

        // Assign the element to be inserted to the specified index position
        newArr[index] = element;

        // Assign the indexed data to the new array
        System.arraycopy(arr, index, newArr, index + 1, arr.length - index);

        // Return new array
        return newArr;
    }

Delete the element at the specified index of the array

Using the method of fori loop

public class Calculate {
    public static void main(String[] args) {

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

        System.out.println("The current array value is:" + Arrays.toString(arr)); // [1, 2, 3, 4, 5]

        // Delete an element at the position of array index 2: then the deleted array should be: {1, 2, 4, 5}
        arr = arrDeleteElementByIndex(arr, 2);

        // After inserting data, the value of the array is:
        System.out.println("After deleting the element, the value of the array is:" + Arrays.toString(arr)); // [1, 2, 4, 5]
    }

    public static int[] arrDeleteElementByIndex(int[] arr, int index) {
        // Since the length of the array cannot be changed after it is created, a new array is needed to store data. Because an element needs to be deleted, the length of the array needs to be reduced by one on the basis of the original array
        int[] newArr = new int[arr.length - 1];

        // Assign the data before the index to the new array
        for (int i = 0; i < index; i++) {
            newArr[i] = arr[i];
        }

        // Assign the indexed data to the new array
        for (int i = index; i < arr.length -1; i++) {
              newArr[i] =  arr[i + 1];
        }

        // Return new array
        return newArr;
    }
}

Implemented using the System.arraycopy() method

  • Only the code of the arrDeleteElementByIndex() method is provided here
    public static int[] arrDeleteElementByIndex(int[] arr, int index) {
        // Since the length of the array cannot be changed after it is created, a new array is needed to store data. Because an element needs to be deleted, the length of the array needs to be reduced by one on the basis of the original array
        int[] newArr = new int[arr.length - 1];

        // Assign the data before the index to the new array
        System.arraycopy(arr, 0, newArr, 0, index);

        // Assign the indexed data to the new array
        System.arraycopy(arr, index + 1, newArr, index, arr.length - index - 1);

        // Return new array
        return newArr;
    }

Explanation of parameters of System.arraycopy() method (5 parameters)

/*
 * Function: copy the entire array
 * Object src: Raw array
 * int srcPos: Copy from the subscript of the original array
 * Object dest:  Target array, that is, to copy into this array
 * int destPos: Copy from the subscript of the target array
 * int length:  How many elements need to be copied
 * Tip: the source array and the target array must be of the same type
*/

String string

How to create strings and constant pools

// 1. Create a String object
// The virtual opportunity creates a String object in the Eden area of the heap memory
String str1 = new String("it's a nice day today Abc");

// The virtual opportunity puts the string directly into the constant pool
String str2 = "it's a nice day today Abc";
String str3 = "it's a nice day today Abc";

// Judge whether the addresses of two string objects are consistent false
System.out.println(str1 == str2);

// Judge whether the addresses of two string objects are consistent. This is because of the existence of constant pool
System.out.println(str2 == str3);

Basic methods of String object

// 1 judge whether the contents of two strings are equal
System.out.println(str1.equals(str2));

// 2 get the length of the string
System.out.println(str1.length());

// 3 remove spaces at both ends of the string
System.out.println(str1.trim());

// 4 judge whether the string is empty (judge whether the length is 0)
System.out.println(str1.isEmpty());

// 5 judge whether it starts with the specified string
System.out.println(str1.startsWith("Today's weather"));

// 5 judge whether it ends with the specified string
System.out.println(str1.endsWith("Abc"));

// 6 convert English letters in the string to all uppercase
System.out.println(str1.toUpperCase());

// 7 convert English letters in the string to all lowercase
System.out.println(str1.toLowerCase());

// 8 judge whether the string contains the specified string
System.out.println(str1.contains("The weather is not good today."));

// 9 intercept the string,
    // 9.1 get all elements from the index position and beyond
    str1.substring(0);
    // 9.2 start from the position of string index 2 and intercept to the position of index 3 (because it contains the head but not the tail)
    str1.substring(2, 4);

Other methods of String object

// 1 find the character specified in the string according to the index
System.out.println(str1.charAt(0));

// 2 find the index position of the first occurrence according to the string, from left to right
System.out.println(str1.indexOf("Abc"));

// 3 find the index position of the first occurrence according to the string, from right to left
System.out.println(str1.lastIndexOf("Abc"));

// 4 replace the found string with another string, and only replace the first matching string found
System.out.println(str1.replace("today", "tomorrow"));

// 5 replace the found string (the search rule can be a regular expression) with another string, and replace several if found
System.out.println(str1.replaceAll("today", "tomorrow"));

// 6 convert the string into a byte array. A Chinese character occupies 3 bytes in UTF-8, one letter and one byte
byte[] buf = str1.getBytes();
System.out.println(Arrays.toString(buf));

// 7 convert byte array to string
str1 = new String(buf);
System.out.println(str1);

Principle of String class (underlying structure, when two strings are spliced)

1. String Class is a final Decorated class, which cannot be inherited
2. The underlying storage of data is actually a character array final char value[],See that the string is**Immutable**of
3. When two strings are spliced, the**Create a new character array**,It is easy to splice two strings together**Affect efficiency**

StringBuffer and StringBuilder

What are StringBuffer and StringBuilder?

It is a variable character sequence, and the bottom layer is a character array without final decoration. The methods of these two objects are the same.

Common methods of StringBuffer/StringBuilder

StringBuilder str = new StringBuilder();

// Additional content
str.append("abc");
// Insert content at the specified index
str.insert(1, "d");
// Delete data at the specified index
str.deleteCharAt(0);
// Delete data for the specified index range
str.delete(0, 1);
// Intercept string
str.substring(2, 3);

// Invert string
str.reverse();
// Replace the elements of indexes 0~2 with ddd
str.replace(0, 2 ,"abc");
// Convert it to String
System.out.println(str.toString());

When will StringBuffer and StringBuilder be used?

  • Because the bottom layer of String is an immutable character array, the efficiency of String splicing will be very low

  • Therefore, if there are many string splicing operations, you can use the variable character sequence StringBuffer or StringBuilder

When to use StringBuffer? When to use StringBuilder?

  • StringBuffer is thread safe, which means that the efficiency will be lower, so it can be used in multithreading.

  • StringBuilder is thread unsafe and fast. Used when there is no thread safety problem.

Posted by phpfan on Thu, 28 Jul 2022 22:15:23 +0530