2014-10-05 31 views
2

我想复制一个数组没有指定的元素。比方说,我有以下阵列:复制数组没有指定的元素java

int[] array = {1,2,3,4,5,6,7,8,9}; 
int[] array2 = new int[array.length-1]; 

我要的是复制数组不包含的int元素数组2“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

什么是“tab”和“tab2”?和“但它不工作”不是一个错误信息的好替代品。 – Tom 2014-10-05 21:58:11

+0

我的不好,选项卡是数组,而tab2是数组2 – 2014-10-05 22:02:30

+0

什么不工作?你有错误吗?另一个结果?什么都没有? – 2014-10-05 22:07:32

回答

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]; 
} 
+0

谢谢但array2的最后一个元素没有被复制,出现0而不是9 – 2014-10-05 22:09:05

+0

@BobJ我猜你忘了把'int count = 0;'改成'int count = 1;'? – Tom 2014-10-05 22:10:21

+0

不能将array.length2而不是array.length。谢谢你的工作 – 2014-10-05 22:13:01

1

您也可以使用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]