3 回答

TA貢獻1810條經驗 獲得超4個贊
您可以使用如下所示的一些代碼獲得相同的結果:
// Add to params all inputs to remove from array
List<Integer> params = new ArrayList<>();
// Use Integer class instead of int datatype
Integer array[] = new Integer[] {0,1,2,3,4,3};
// Convert array to List class
List<Integer> list = new ArrayList<>(Arrays.asList(array));
// Remove all matches
list.removeAll(params);

TA貢獻1859條經驗 獲得超6個贊
您需要兩個索引變量來進行復制:一個貫穿輸入數組(如原始代碼中所示),另一個跟蹤您在輸出數組中的位置(new 變量)。它們不能相互計算(它們在開始時是相同的,但可以明顯小于最后)abba
int b = 0;
for(int a = 0; a < in.length; a++) {
if(in[a] != v) {
copy[b] = in[a];
b++;
}
}

TA貢獻2003條經驗 獲得超2個贊
使用Java8及其流功能,您可以執行如下操作:
public static void main(String[] args) {
int[] array = {3236,47,34,34,73,46,3,64,473,4,4,346,4,63,644,4,6,4};
int[] newArray = removeAllOccurencesOf(array, 4);
System.out.println(Arrays.toString(newArray));
}
public static int[] removeAllOccurencesOf(int[] array, int numberToRemove)
{
//stream integers from array, filter the ones that correspond to number to remove, get what's left to new array
int[] newArray = IntStream.of(array).filter(i->i!=numberToRemove).toArray();
return newArray;
}
添加回答
舉報