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

问题描述

我有一个任务,要创建一个方法获取字符串数组的元素,检查是否有重复项,然后删除它(我用“null”尝试过),然后将所有其他元素移向索引值 [0] 以关闭间隙。

现在看起来像这样:

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){
                //set pos+1 = pos to reduce each value -1. 
                //repeat process for each index [10]
                }
            }
        }
        return removed;
    }
}

图片中,我展示了我所看到的结果。 例如。 pos.4 是重复的 - 然后将其设置为 null。现在必须将以下所有索引更改为 -1 以填补空白。 显然,然后将索引设置回 456 而不是 567 这只是为了说明字符串的移动。

你能帮我在 [pos] null 之后在 -1 方向移动索引吗?

如果你能帮助对 2 个以上的重复做同样的事情,那就更好了。

changingElementsIndexesInArrayJava

解决方法

您可以使用Arrays.stream方法遍历这个数组的元素,filter去掉不需要的元素,或者只保留distinct元素,重新组装相同长度的数组如下:

String[] arr = {"aaaa","cccc","aaaa","bbbb","aaaa"};

System.out.println(Arrays.toString(arr)); // [aaaa,cccc,aaaa,bbbb,aaaa]
String[] arr1 = Arrays.stream(arr)
        .filter(s -> !s.equals("aaaa"))
        .toArray(q -> new String[arr.length]);

System.out.println(Arrays.toString(arr1)); // [cccc,null,null]
String[] arr2 = Arrays.stream(arr)
        .distinct()
        .toArray(q -> new String[arr.length]);

System.out.println(Arrays.toString(arr2)); // [aaaa,null]

另见:
How to find duplicate elements in array in effective way?
How to get elements of an array that is not null?

,

代替

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

使用数组时,您要么向下移动值以缩小差距,要么只是将元素复制到一个新的较小数组中。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...