简体   繁体   中英

Java: Remove all instances of a certain item in an array

Suppose I make an array, setting the values as follows:

double[] exampleArray = {10.0, 3.0, 0.0, 0.0, 0.0};

How can I remove all the 0.0 's from the array, leaving only 10.0 and 3.0 and shortening the array length to 2?

The other questions on this site involve HashSets or Collections . Is there a way without importing other stuff?

这是一个使用流可以完成工作的单线程:

exampleArray = Arrays.stream(exampleArray).filter(d -> d != 0.0).toArray();

This is just an example using the int datatype. It can be changed to suit your needs.

Explanation: j is a counter variable that is used to size newArray by excluding non-zero indexes from the creation of a new array and copying all non-zero indexes to the new array. We do this because array length is immutable in java. Therefore, when attempting to resize an array, one must create a new array and copy. This is the benefit of using other data structures when size mutability is required.

int j = 0;
for( int i=0; i<array.length; i++ ){
    if (array[i] != 0)
        array[j++] = array[i];
}
int [] newArray = new int[j];
System.arraycopy( array, 0, newArray, 0, j );

Hope this code can help you. It is the most basic (not best) approach:

double[] exampleArray = {10.0, 3.0, 0.0, 0.0, 0.0}; 
double numberToErase = 0.0; //This could be a parameter
int newArraySize = 0;

//Get the fixed size of the new Array
for (double n : exampleArray) {
    if (n != numberToErase) {
        newArraySize++;
    }
}

//Create the new array 
double[] newArray = new double[newArraySize];
int newArrayCurrentIndex = 0;
for (double n : exampleArray) {
    if (n != numberToErase) {
        newArray[newArrayCurrentIndex++] = n;
    }
}

//Check the result
for (double n : newArray) {
    System.out.println("Number: " + n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM