简体   繁体   中英

How to shift elements in array?

I am trying to create a method that searches through the 'data' array to find the string 'elt'. If it exists, it shifts all elements after 'elt' one position to the left (to cover the cell where 'elt' existed).

I am able to find all instances of "elt" and set them to null, but I am having problems shifting all elements past "elt" down one space in the array. The code below is what I have so far.

public class Bag<T> implements Iterable<T> {

private final int MAXLEN = 3;
private int size;
private T[] data; // array

public T remove(T elt) {

        for (int i=0; i<data.length; i++) {
            if ("elt".equals(data[i]) ) {
                data[i] = null;

                for (i++; i < data.length; i++) {
                    data[i] = data[i-1];
                }
            }
        }
public static void main(String[] args) {
        Bag<String> sbag = new Bag<String>();

        sbag.add("Noriko");
        sbag.add("Buddy");
        sbag.add("Mary");
        sbag.add("Peter");
        sbag.add("elt");
        sbag.add("hello");

    Iterator<String> it = sbag.iterator();
        while (it.hasNext()) {
            String val = it.next();
            System.out.println(val);
        }

    sbag.remove("elt");

    Iterator<String> it2 = sbag.iterator();
        while (it2.hasNext()) {
            String val = it2.next();
            System.out.println(val);
        }
}

When I run that code, I get:

Noriko Buddy Mary Peter elt hello Noriko Buddy Mary Peter null

However, I am expecting

Noriko Buddy Mary Peter elt hello Noriko Buddy Mary Peter hello

Can anybody tell me how I can fix the code so that the rest of the items in the array are shifted down? I think the problem is in my remove method.

If i understand what you're trying to achieve correctly, you're shifting the wrong way you want:

public T remove(T elt) {

    for (int i=0; i<data.length; ++i) {
        if (elt.equals(data[i]) ) {
            data[i] = null;
            for (++i; i < data.length; ++i) {
                data[i-1] = data[i];
            }
            break;
        }
    }

`

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