简体   繁体   中英

How do I shift array elements up one position in java?

I am working on a java assignment where I need to delete an integer element in an array and shift the below elements up on space to keep them in order. The array is currently random integers in descending order. I am not allowed to use array.copy because I will need to collect array usage information as part of the assignment. I have tried a ton of different ways of doing this but cannot seem to get it working.

public static void deletionArray(int anArray[], int positionToDelete) {
    for (int j = anArray[positionToDelete] - 1; j < anArray.length; j++) {
        System.out.println("j is " + j);
        anArray[j] = anArray[j + 1];
    }

    displayArray(anArray);
}   

You're iterating until anArray.length (exclusive), but inside the loop, you're accessing anArray[j + 1] , which will thus be equal to anArray[anArray.length] at the last iteration, which will cause an ArrayIndexOutOfBoundsException.

Iterate until anArray.length - 1 (exclusive), and decide what should be stored in the last element of the array instead of its previous value.

You're also starting at anArray[positionToDelete] - 1 , instead of starting at positionToDelete .

You have two bugs there.

Since this is an assignment, I won't give a complete answer - just a hint. Your loop definition is wrong. Think about this: what happens on the first and on the last iteration of the loop? Imagine a 5-element array (numbered 0 to 4, as per Java rules), and work out the values of variables over iterations of the loop when you're erasing element number, say, 2.

Use System.arraycopy faster than a loop:

public static void deletionArray( int anArray[], int positionToDelete) {
    System.arraycopy(anArray, positionToDelete + 1, anArray,
            positionToDelete, anArray.length - positionToDelete - 1);
    //anArray[length-1]=0;        //you may clear the last element 
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
    if (anArray.length == 0) {
        throw new IlligalArgumentException("Error");
    }
    int[] ret = new int[anArray.length - 1];
    int j = 0;
    for (int i = 0; i < anArray.length; ++i) {
        if (i != positionToDelete) {
            ret[j] = anArray[i];
            ++j;
        }
    }
    return ret;
}

Why do we reserve a new array?

Because if don't, we would use C\\C++-style array: an array and a "used length" of it.

public static int deletionArray(int anArray[], int positionToDelete, int n) {
   if (n == 0) {
       throw new IlligalArgumentException("Error");
   }
   for (int i = positionToDelete; i < n - 1; ++i) {
       anArray[i] = anArray[i + 1];
   }
   return n - 1; // the new length
}

How's this ? Please note the comment, I don't think you can delete an element in an array, just replace it with something else, this may be useful : Removing an element from an Array (Java)

Updated with 'JB Nizet' comment :

public class Driver {

    public static void main (String args []){

        int intArray[] = { 1,3,5,6,7,8};
        int updatedArray[] = deletionArray(intArray , 3);

         for (int j = 0; j < updatedArray.length; j++) {    
             System.out.println(updatedArray[j]);
         }

    }

    public static int[] deletionArray(int anArray[], int positionToDelete) {
        boolean isTrue = false;


           for (int j = positionToDelete; j < anArray.length - 1; j++) {            
                if(j == positionToDelete || isTrue){
                    isTrue = true;
                    anArray[j] = anArray[j + 1];
                }

            }

        anArray[anArray.length-1] = 0; //decide what value this should be or create a new array with just the array elements of length -> anArray.length-2
        return anArray;
    }
}

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