Java刪除陣列指定元素,並壓縮陣列
阿新 • • 發佈:2018-11-05
定義原陣列和接收結果的陣列
int[] array1 = new int[]{1, 8, 6, 5, 7, 12, 31, 89, 100};
int[] result;
printArray(array1);
result = resetArray(array1, 31);
printArray(result);
//下面是具體實現方法
private int[] resetArray(int[] array1, int element) {
int index = -1;
for (int i = 0; i < array1.length ; i++) {
if (array1[i] == element) {
index = i;
break;
}
}
if (index == -1) {
//如果不含這個元素,就原樣返回
return array1;
}
int[] array2 = new int[array1.length - 1];
if (index == array1.length - 1) {
array2 = Arrays.copyOf(array1, array1.length - 1);
} else {
for (int i = 0; i < array1.length; i++) {
if (i < index) {
array2[i] = array1[i];
} else if (i >= index && i < array1.length - 1) {
array2[i] = array1[i + 1 ];
}
}
}
return array2;
}
//列印陣列
private void printArray(int[] array) {
String result = "[";
for (int i = 0; i < array.length; i++) {
result = result + array[i] + ",";
if (i == array.length - 1) {
result = result.substring(0, result.length() - 1) + "]";
}
}
System.out.println("輸出:" + result);
}
下面是執行之後的結果