java - java - 如何使用java中的索引删除()ArrayList()中的字符串元素序列?
问题描述
我想在我的代码中删除序列字符串元素中的 4 个索引。我的 ArrayList 包含多个 String 元素:
{MyString,MyString1,MyString2,MyString3,MyString4,...., MyString10}
这是我的代码:
String removedItem = "MyString";
for (int i = 0; i < myArrayList.size(); i++) {
if (myArrayList.get(i).equals(removedItem)) {
myArrayList.remove(i);
myArrayList.remove(i+1);
myArrayList.remove(i+2);
myArrayList.remove(i+3);
}
}
System.out.println(myArrayList);
我的代码似乎没有按顺序删除前 4 个索引。我做错了什么,我该如何解决?任何帮助将不胜感激!
解决方案
如果你想删除指定的值和接下来的三个元素。你可以使用这个:
for (int i = 0; i < myArrayList.size(); i++) {
if (myArrayList.get(i).equals(removedItem)) {
myArrayList.remove(i);
myArrayList.remove(i);
myArrayList.remove(i);
myArrayList.remove(i);
}
}
因为每次删除一个元素,下一个元素都会向前移动。
推荐阅读
- java - Java Spring Boot SwaggerUI
- javascript - Javascript:如何从 servlet 获取和打印数据
- html - 选择表单时是否可以将表单数据发送到服务器?
- amazon-sqs - AWS JDK 2 创建队列并订阅主题
- web-scraping - 谷歌importhtml动态表需要最后10个板球得分
- google-bigquery - 将参数化 BigQuery 自定义查询连接到数据洞察
- javascript - 如何在我的 React 类的接口中包含接口?
- java - Android删除sdcard中的文件
- java - 用 groovy 读取 Excel(.xlsx 或 .csv)
- smartsheet-api - 如何使用 Smartsheet API 检测“Sheet - Create”