首页 > 解决方案 > 如何删除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;  
    }  
}

标签: java

解决方案


尝试这个。

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();
    }
}

推荐阅读