The basic use of arrays in java

One, the array

1. The basic use of arrays
For detailed usage, refer to the code examples on Github

 

2. Increase of array elements

 

public class Test {
    public static void main(String[] args) {
        int[] arr = new int[] {6,7,8};
        System.out.println(Arrays.toString(arr));
        //要加入的目标元素
        int dst = 9;
        //创建新数组
        int[] newArr = new int[arr.length+1];
        //复制数据
        for (int i=0; i<arr.length; i++) {
            newArr[i] = arr[i];
        }
        newArr[arr.length] = dst;
        System.out.println(Arrays.toString(newArr));
    }
}
3. Deletion of array elements

 

public class Test {
    public static void main(String[] args) {
        int[] arr = new int[] {6,7,8,9};
        System.out.println(Arrays.toString(arr));
        //要删除元素的下标
        int dst = 3;
        //创建新数组
        int[] newArr = new int[arr.length-1];
        //复制数据
        for (int i=0; i<newArr.length; i++) {
            if (i < dst) {
                newArr[i] = arr[i];
            }else {
                newArr[i] = arr[i+1];
            }
        }
        arr = newArr;
        System.out.println(Arrays.toString(arr));
    }
}

Guess you like

Origin blog.csdn.net/Beer_xiaocai/article/details/87807555