且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从字符串数组中删除元素后,如何减少元素的索引?

更新时间:2023-11-13 17:22:22

代替

todos[pos + 1] = todos[pos];

您应该使用

todos[pos] = todos[pos + 1];

这是工作代码:

public static boolean deleteTask() {
    boolean removed = false;
    for (int pos = 0; pos < todos.length; pos++) {
        if (todos[pos].equals(titel)) {
            todos[pos] = null;
            removed = true;
        }
        if (removed && pos < todos.length - 1) {
            // swap the string with the next one
            // you can't do this with the last
            // element because [pos + 1] will
            // throw an indexoutofbounds exception
            todos[pos] = todos[pos + 1];
        } else if (removed && pos == todos.length - 1) {
            // here you can swap the last one with null
            todos[pos] = null;
        }
    }
    return removed;
}