我需要使用“remove”方法,该方法接受字符串的 ArrayList 和目标字符串作为两个参数,并从 ArrayList 中搜索并删除所有匹配的字符串。例如,在 ArrayList [“Go”、“Go”、“Go”] 和目标字符串“Go”上调用remove,将导致一个空的 ArrayList。
public class Remove {
public static void main (String [] args) {
ArrayList<String> x = new ArrayList<>();
x.add("Go");
x.add("Go");
x.add("Go");
System.out.println(x);
remove("Go");
System.out.println(x);
}
public static void remove(String t) {
ArrayList<String> x = new ArrayList<>();
for(int i = 0; i < x.size(); i++) {
if(x.get(i).equals(t)) {
x.remove(i);
i--;
}
}
}
}
最佳答案
remove
方法创建一个新的ArrayList
,然后尝试从中删除一个值。相反,您应该将一个列表传递给该方法。此外,使用 JDK 8 的 removeIf
方法将使您的代码更加简单:
public static void main (String [] args) {
List<String> x = new ArrayList<>();
x.add("Go");
x.add("Go");
x.add("Go");
System.out.println(x);
remove(x, "Go");
System.out.println(x);
}
public static void remove(List<String> list, String t) {
list.removeIf(s -> s.equals(t));
}
关于java - 使用 JAVA 子方法从数组中删除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52338810/