我尝试复制没有指定元素的数组。让我们说我有以下数组:
int[] array = {1,2,3,4,5,6,7,8,9};
int[] array2 = new int[array.length-1];
我想要的是将数组复制到array2而不包含int" 6"所以它将包含 " {1,2,3,4,5,7,8,9}"
我只想使用for循环,这是我到目前为止所做的但它不起作用
int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] array2= new int[array.length - 1];
int remove = 6;
for (int i = 0; i < array2.length; i++) {
if (array[i] != remove) {
array2[i] = array[i];
} else {
array2[i] = array[i + 1];
i++;
}
}
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
由于
答案 0 :(得分:4)
int j = 0;
int count = 0; //Set this variable to the number of times the 'remove' item appears in the list
int[] array2 = new int[array.length - count];
int remove = 6;
for(int i=0; i < array.length; i++)
{
if(array[i] != remove)
array2[j++] = array[i];
}
答案 1 :(得分:3)
您也可以使用Java 8的流和lambda表达式来完成它:
int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] array2 = Arrays.stream( array ).filter( value -> value != 6 ).toArray();
System.out.println( Arrays.toString( array2 ) );
// Outputs: [1, 2, 3, 4, 5, 7, 8, 9]