我有一个实现接口的类,我想当我尝试一次将元素插入数组中的次数超过一次被忘记的时候。我真的不知道这一点。这就是我所拥有的:

public void insertElementAt(int index, E el)
                 throws IllegalArgumentException {

    Object temp[] = new Object[data.length + 1];
    for (int i = 0; i < data.length; i++) {
        if (i == index){
            temp[index] = el;
            temp[i + 1] = data[i];
            i++;
        }

        temp[i] = data[i];
    }

    data = temp;

    if (index > data.length || index < 0) {
        throw new IllegalArgumentException();
    }
}


然后,我的测试报告null而不是最后一个断言。

@Test
public void testInsertToLeft() {
    PriorityList<String> list = new ArrayPriorityList<String>();
    list.insertElementAt(0, "First");
    // Must shift array elements in this case
    list.insertElementAt(0, "New First");

    assertEquals("New First", list.getElementAt(0));
    assertEquals("First", list.getElementAt(1));
}

最佳答案

您必须这样做:

public void insertElementAt(int index, E el) throws IllegalArgumentException {

    Object temp[] = new Object[data.length + 1];
    for (int i = 0; i < data.length; i++) {
        if (i >= index){
            temp[i + 1] = data[i];
        } else {
            temp[i] = data[i];
        }
    }
    temp[index] = el;
    data = temp;

    if (index > data.length || index < 0) {
        throw new IllegalArgumentException();
    }
}


删除它:

public void removeElementAt(int index) throws IllegalArgumentException {

    Object temp[] = new Object[data.length - 1];
    for (int i = 0; i < temp.length; i++) {
        if (i > index){
            temp[i - 1] = data[i];
        } else {
            temp[i] = data[i];
        }
    }
    data = temp;

    if (index > data.length || index < 0) {
        throw new IllegalArgumentException();
    }
}

10-05 21:34