Java:数组的扩容与缩容

前言:

        记录数组的扩容与缩容!

扩容:

        现有数组int[] arr = new int[]{1,2,3,4,5},需要将数组长度扩容1倍,并将10,20,30三个数据添加到arr数组中。

扩容一倍有两种写法。

int[] newArr = new int[arr.length * 2];
//或是
int[] newArr = new int[arr.length << 1];
int[] arr = {1, 2, 3, 4, 5};
int[] newArr = new int[arr.length << 1]; //new int[arr.length * 2];
for (int i = 0; i < arr.length; i++) {
    newArr[i] = arr[i];
}
newArr[arr.length] = 10;
newArr[arr.length + 1] = 20;
newArr[arr.length + 2] = 30;
System.out.println(Arrays.toString(newArr)); //[1, 2, 3, 4, 5, 10, 20, 30, 0, 0]

缩容:

        现有数组int[] arr = {1,2,3,4,5,6,7}。现需要删除数组中索引为4的元素,即5,得到[1,2,3,4,6,7]

第一种:

int[] array = {1, 2, 3, 4, 5, 6, 7};
int deleteIndex = 4;

for (int i = deleteIndex; i < array.length - 1; i++) {
    array[i] = array[i + 1];
}
array[array.length - 1] = 0;
int[] newArray = new int[array.length - 1];
for (int i = 0; i < newArray.length; i++) {
    newArray[i] = array[i];
}
array = newArray;
System.out.println(Arrays.toString(array));  //[1, 2, 3, 4, 6, 7]

第二种:

int[] array = {1, 2, 3, 4, 5, 6, 7};
int deleteIndex = 4;        
int[] newArray = new int[array.length - 1];
for (int i = 0; i < deleteIndex; i++) {
     newArray[i] = array[i];
}
for (int i = deleteIndex; i < array.length - 1; i++) {
     newArray[i] = array[i + 1];
}
array = newArray;
System.out.println(Arrays.toString(array));

你可能感兴趣的:(Java,java)