简体   繁体   English

如何移动数组中的元素?

[英]How to shift elements in array?

I am trying to create a method that searches through the 'data' array to find the string 'elt'. 我正在尝试创建一种在“数据”数组中进行搜索以找到字符串“ elt”的方法。 If it exists, it shifts all elements after 'elt' one position to the left (to cover the cell where 'elt' existed). 如果存在,则会将“ elt”之后的所有元素向左移动一个位置(以覆盖“ elt”所在的单元格)。

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. 我能够找到“ elt”的所有实例并将它们设置为null,但是在将所有元素通过“ elt”向下移动到数组中的一个空间时遇到了问题。 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 Noriko Buddy Mary Peter埃尔特你好Noriko Buddy Mary Peter null

However, I am expecting 但是,我期望

Noriko Buddy Mary Peter elt hello Noriko Buddy Mary Peter hello Noriko Buddy Mary Peter问候你好Noriko Buddy Mary Peter问候你好

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;
        }
    }

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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