如何解决删除元素后,如何减少字符串数组中元素的索引?
我有一个任务,要创建一个方法来获取字符串数组的元素,检查是否有重复项,然后删除它(我用“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 个以上的重复做同样的事情,那就更好了。
解决方法
您可以使用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;
}
,
使用数组时,您要么向下移动值以缩小差距,要么只是将元素复制到一个新的较小数组中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。