java - 如何删除arraylist中的特定行
问题描述
如何在尝试执行此操作时从 ArrayList 中删除特定行,但执行后仍显示在 ArrayList 上?例如,如果我想删除 rollno: 2,BBB,14。我应该如何从 ArrayList 而不是其他两个中删除它。我尝试将 itr.remove 放在下面评论中提到的 while 循环中,但仍然没有运气,它仍然显示在数组列表中并且没有任何内容被删除。
公共类 StudentDB{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
/* while(itr.hasNext()){
Student st=(Student)itr.next();
if(st.rollno == 2){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
else{
continue;
}
} */
//Scanner scan = new Scanner(System.in);
System.out.println("ENter your id: ");
int id = scan.nextInt();
boolean result = false;
while(!result) {
while(itr.hasNext()) {
Student st=(Student)itr.next();
if(st.rollno == id){
result = true;
break;
}
else{
result = false;
}
}
}
if(result == true){
System.out.println("Roll no found!");
}else{
System.out.println("Roll no not found!");
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
解决方案
尝试这个。
System.out.println("Enter id to remove: ");
int id = scan.nextInt();
Iterator<Student> itr = al.iterator();
while (itr.hasNext()) {
if (itr.next().rollno == id) {
itr.remove();
}
}
推荐阅读
- html - HTACCESS 301 重定向解决谷歌搜索控制台中的重定向错误?
- java - 在 Kotlin 中单击通知时如何停止播放音频?
- html - 如何以正确的格式在 html 中显示 T-SQL?
- mysql - maxscale 代理不会将来自 flask-sqlachamy 的读取请求路由到从属设备
- angular - Wordpress REST API V2 仅返回 10 个帖子
- database - Go 中的 MongoDB 连接错误:目标机器主动拒绝连接。使用来自 Mongo 网站的代码
- git - Git 提交了所有内容,但仍然出现错误:您对以下文件的本地更改将被结帐覆盖
- javascript - 如何获取兄弟元素的内部html文本
- node.js - 如何切换或更改 Input.ChoiceSet 以响应其他 Input.ChoiSet 值?
- reactjs - 如何在 Antd 中使用动态表单嵌套