简体   繁体   中英

How to shift array elements after removing one?

I need to add a shift function only with loops (it means I can't use any ListArray method et simila, so this is not a copy of any other question with those methods.) to this method which removes a specific integer from a given array, and put the outcome into another array, and then returning it.

public static int[] removeInt(int v, int[] in) {

    int length = 0;
    length = in.length;
    int[] toReturn = new int[length];

    for (int b = 0; b < length; b++) {
        toReturn[b] = 0;
    }

    for (int i = 0; i < length; i++) {
        if (in[i] != v) {
            toReturn[i] = in[i];
        }
    }

    return toReturn;
}

If the input for the array is {1, 2, 3, 4, 5}, and the number to remove is {2}, the output will be {1 0 3 4 5}, but it needs to be {1 3 4 5}, and I can't find a way to shift numbers to the left.

'v' comes from the main, user input. Same for 'in', fullfilled before by the user.

Have you considered using a LinkedList ? This internally manages the array so you don't need to deal with moving the elements yourself; you can just call remove() .

You will have to iterate over the array two times: The first time, you count how often v is contained in in . If count is 0, you can return in, otherwise you would have to create a new array of length in.length - count . Then again you have to iterate over in and add every value that is not v to your Array.

int count = 0;

    for(int i: in) {
        if (i==v) {
            count++;
        }
    }

    int[] result = new int[in.length-count];
    int pos=0;
    for(int i: in) {
        if (i!=v) {
            result[pos] = i;
            pos++;
        }
    }

But you could use Collections to make it easier:

public static void main(String[] args) {
    int v = 2;
    int[] in = new int[]{1, 2, 3, 4, 5};

    List<Integer> list = new ArrayList<>();
    for(int i: in) {
        if (i!=v) {
            list.add(i);
        }
    }

    Integer[] result = list.toArray(new Integer[]{});
}

The disadvantage of this, however, would be that you have an Array of Integer and not of int.

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