How to quickly insert a data at the end of the array (java)

topic

Insert a data at the end of the array.
Test example:
    Before tail plugging: 1 2 3 After
    tail plugging: 1 2 3 99

Ideas:

We know that an array is a continuous area in the memory. Once opened, it cannot be resized at will, only new space can be created.
With the help of the Arrays.copyOf() function, you can quickly adjust the size of the array, and then insert a data at the end.

Code:

import java.util.Arrays;
public class Main {
    
    
	public static int[] insertTail(int[] arr, int value) {
    
     // 1 2 3 [value]
		// 参数安全检测 int[] 引用数据类型 默认值 null
		if (arr == null) {
    
    
			return null;
		}
		// 1. 扩容+1
		arr = Arrays.copyOf(arr, arr.length + 1);
		// 2. 向arr 尾部添加一个数据value
		arr[arr.length - 1] = value;
		return arr;
	}

	public static void main(String[] args) {
    
    
		int[] arr = {
    
     1, 2, 3 };
		arr = insertTail(arr, 99);
		System.out.println(Arrays.toString(arr));
	}
}

Guess you like

Origin blog.csdn.net/qq_41571459/article/details/113094759