[英]copy array without specified element java
i'm trying copy an array without a specified element.我正在尝试复制一个没有指定元素的数组。 Let's say I have the following arrays:假设我有以下 arrays:
int[] array = {1,2,3,4,5,6,7,8,9};
int[] array2 = new int[array.length-1];
what I want is to copy array to array2 without the element containing the int "6" so it will contain "{1,2,3,4,5,7,8,9}"我想要的是将数组复制到 array2,而不包含包含 int“6”的元素,因此它将包含“{1,2,3,4,5,7,8,9}”
I only want to use for loops and this is what I have so far but it doesnt work我只想使用 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]);
}
Thanks谢谢
You can also do it using Java 8's streams and lambda expressions: 您也可以使用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]
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];
}
ArrayUtils.remove(array, 6)
from apache.commons.lang might also be suitable来自apache.commons.lang的ArrayUtils.remove(array, 6)
可能也适用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.