【发布时间】:2019-04-01 07:16:30
【问题描述】:
我会保持简单: 我有一个名称的 ArrayList,我必须删除某些包含特定字母的单词,但我无法重新启动 for 循环。这是我得到的:
public static void someRandomFunction(){
List<String> arrList = new ArrayList<>(Arrays.asList("Hello",
"Everyone",
"I'm",
"Struggling",
"In",
"Computer",
"Science"));
System.out.println("Start of List: " + wordList + "\n");
System.out.println("\nDrop: \"a\"");
someRandomFunction(wordList, "a");
System.out.println("wordList is now: " + wordList);
}
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 will not work because of incompatible types.
}
编译后的代码示例:
ArrayList [大家好,我是,我,正在努力,在,计算机,科学]
删除以“A”开头的单词:
新的 ArrayList [大家好,我是 Struggling,In,Computer,Science]
删除以“I”开头的单词:
新的 ArrayList [Hello, Everyone, Am, Struggling, Computer, Science]
我的代码的问题在于,当它开始读取它需要删除的新单词时,它不会将单词列表返回到以前的状态。
【问题讨论】:
-
如果您需要保留原始状态,请在进行更改之前复制列表。
List<String> wordListCopy = new ArrayList<>(wordList) -
您需要对同一个列表进行更改还是可以使用新列表?
-
否,因此该列表已经以特定方式设置。我没有更改 ArrayList。我只希望它适用于我必须删除以特定字母开头的单词的每个实例。
-
为什么不创建一个新列表,其中包含不留在字母中的单词并使用它?
标签: java arrays for-loop arraylist while-loop