简体   繁体   中英

Understanding the logic of an add to an array method

This method is used to insert the element toAdd as the new first element of the array arr, shifting all of the current elements over to make space. The original last element of the array will just be lost. The method has no return value and if the array has no elements it should have no effect.

public static void insert(int[] arr, int toAdd){

    if(arr.length > 0) {

        for(int i = arr.length - 1; i > 0; --i) {
            arr[i] = arr[i - 1];
        }
        arr[0] = toAdd;
    }
}

I understand the part about if(arr.length > 0) this guarantees that we are working with an array with at least 1 element. The rest of the logic confuses me. Why set i = arr.length, why a - 1 afterward? why i > 0? and --i?

Thank you

You are browsing your array from its last element to the first, while shifting each element over by one. For example, when i = 3 we moving element 2 to position 3.

But this method doesn't work. A correct version would be:

public static void insert(int[] arr, int toAdd){
    if(arr.length > 0) {
        for(int i = arr.length - 1; i > 0; i--) {
            arr[i] = arr[i - 1];
        }
        arr[0] = toAdd;
    }
}

--i reduce the value of i before its use so it should be i-- or i should begin at arr.length or else you won't move the last element.

Why set i = arr.length and --i?

It is i = arr.length-1 and this the last index of the array. You have to start shifting elements looping backwards ( --i , i-- would be ok, too), otherwise you'll be overriding elements before you can shift them.

why i > 0?

arr[0] = toAdd; should be outside of the loop and would fail for arr.length == 0 .

You can simplify to:

public static void insert(int[] arr, int toAdd){
    if(arr.length > 0) {
        for(int i = arr.length - 1; i > 0; --i)
            arr[i] = arr[i - 1];
        arr[0] = toAdd;
    }
}

arr.length will return the number of elements in the array. If you had an array with elements at index 0, 1, and 2, it would return "3". The problem is that the array index is inclusive at 0, so you need to subtract 1 from the length to get the valid index of the last element in the array. (ie 3 - 1 = 2 and 2 is the true index of the last element)

The loop uses i > 0 because the index i is being decremented (ie i = i -1) by the '--i'. So the loop is starting at the highest element in the array (length -1), and counting down to the lowest (index 0).

Lastly, the line assigning toAdd to 0 should be outside of the for loop.

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