2 回答

TA贡献1784条经验 获得超2个赞
如果您只想删除ArrayList
以某个字母开头的每个元素,您可以使用以下removeIf()
方法:
删除此集合中满足给定谓词的所有元素。
wrodList.removeIf(e -> e.contains(thisLetter));
(需要 Java 8+)
听起来您希望在每次删除元素后重置列表。为此,您可以创建一个副本ArrayList
进行检查,然后在每次之后将其设置回原始副本:
List<String> copy = new ArrayList<>(wordList); //Creates a copy of wordList

TA贡献1785条经验 获得超8个赞
我相信这就是你正在寻找的。我不确定你是想要一个实例还是静态方法。我相信您的问题是您没有创建副本。我记下了我在哪里创建副本。祝你在 CS 中好运......我们都曾一度陷入困境。
public static void someRandomFunction(){
List<String> arrList = new ArrayList<>(Arrays.asList("Hello",
"Everyone",
"I'm",
"Struggling",
"In",
"Computer",
"Science"));
System.out.println(removeIfContains(arrList, "H")); // calling the function and passing the list and what
System.out.println(removeIfContains(arrList, "I")); // I want to remove from the list
}
public static List<String> removeIfContains(List<String> strList, String removeIf){
List<String> tempList = new ArrayList<>(strList); // creating a copy
for(int i = 0; i < tempList.size(); i++){
if(tempList.get(i).contains(removeIf))
tempList.remove(i);
}
return tempList; // returning the copy
}
添加回答
举报