[英]How to remove and replace an item in an array list in Java?
我在Java中有以下代码,
import java.util.ArrayList;
import java.util.Objects;
public class Cars {
private static ArrayList<String> replaceDuplicates(ArrayList<String> aList) {
for (int i = 0; i < aList.size(); i++) {
for (int j = i + 1; j < aList.size(); j++) {
if (Objects.equals(aList.get(i), aList.get(j))) {
aList.remove(i);
aList.add(i, "");
aList.remove(j);
aList.add(j, "");
}
}
}
return aList;
}
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<>();
cars.add("Ford");
cars.add("Ford");
cars.add("Hyundai");
cars.add("Toyota");
cars.add("Toyota");
cars.add("Toyota");
cars.add("Ford");
cars.add("Honda");
cars.add("GMC");
System.out.println(cars);
cars = replaceDuplicates(cars);
System.out.println(cars);
}
}
此代码的输出为- [, , Hyundai, , , Toyota, Ford, Honda, GMC]
我希望替换多次出现在数组列表与汽车的名字" "
。 出于某种原因,在我的代码中,如果汽车的名称在数组列表中出现了三次,那么第三次出现就不会被" "
代替。
我想要的输出应该是这样- [, , Hyundai, , , , , Honda, GMC]
我在这里做错了什么?
先感谢您!
首先,您可以通过使用List.set
而不是插入和删除元素来简化此代码。
aList.remove(i);
aList.add(i, "");
只会变成
aList.set(i, "");
如果两个条目都是重复的,则您要删除它们。 这导致始终删除偶数个条目的行为。 例如:
a b a a c a d a
b a c a d a #first pair removed
b c d a #second pair removed
如果元素数为奇数,则列表中将始终保留一个元素。
显然,您需要某种方式来记住要删除的元素。 一种简单的方法是使用标志来记住是否遇到了元素的重复:
for (int i = 0; i < aList.size(); i++) {
//the flag
boolean duplicate = false;
for (int j = i + 1; j < aList.size(); j++) {
if (Objects.equals(aList.get(i), aList.get(j))) {
aList.set(j, ""); //remove all duplicates with an index higher than i
duplicate = true; //remember that element at index i is a duplicate
}
}
//remove last duplicate element
if(duplicate)
aList.set(i, "");
}
如果仍然要使用方法,则可以在修改列表之前创建对项目的引用:
for (int i = 0; i < aList.size(); i++) {
String a = aList.get(i);
for (int j = i + 1; j < aList.size(); j++) {
String b = aList.get(j);
if (Objects.equals(a, b)) {
aList.remove(i);
aList.add(i, "");
aList.remove(j);
aList.add(j, "");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.