首页 > 解决方案 > 如何从 SortedArrayList 中删除多个元素

问题描述

谁能让我知道我的删除方法有什么问题?我无法从排序的数组列表中删除元素

这是代码

 public static void main(String[] args) {
        SortedListInterface<Student> studList = new SortedArrayList<Student>();
        
        studList.add(new Student("Alex", "20WWW09000","ABC"));
        studList.add(new Student("Cait", "20WDA09080","DEF"));
        studList.add(new Student("Jane", "20WMC09065","GHI"));
        System.out.println(studList);
        studList.remove(new Student("Alex", "20WWW09000","ABC"));
        System.out.println(studList);

这是输出

学生 ID = 20WDA09080 学生姓名 = Cait 课程 = DEF

学生 ID = 20WMC09065 学生姓名 = 简课程 = GHI

学生 ID = 20WWW09000 学生姓名 = Alex 课程 = ABC

学生 ID = 20WDA09080 学生姓名 = Cait 课程 = DEF

学生 ID = 20WMC09065 学生姓名 = 简课程 = GHI

学生 ID = 20WWW09000 学生姓名 = Alex 课程 = ABC

学生 Alex 仍然存在于数组列表中

这是删除方法

public boolean remove(T anEntry) {
       if(isEmpty()){
           return false;
       }
       else{
           int b =0;
          while(b<length && array[b].compareTo(anEntry)<0){
            b++;
       } 
          
         if (array[b].equals(anEntry)) {
            int remove = (b+1) - 1;  //remove the gap
            int last = length -1 ;
            
             for (int c = remove; c < last; c++) {
                 array[c] = array[c+1];
             }

             length --;
             return true;
        }
       }
       return false;

    }

这是学生类(实体类)

public class Student extends Person implements Comparable<Student> {
    
    private String course;
     public Student(String course, String id, String name, String password) {
        super(id, name, password);
        this.course = course;
    }

    public Student(String name, String id, String course) {
        super(id, name);           //I am using this constructor to add the student
        this.course = course;
    }

   

    public Student(String id, String name) {
        super(id, name);
    }


    
    public Student(String id) {
        super(id);
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    
      public int compareTo(Student s){
          
        return thisID().compareTo(s.getId()); 
   }

    @Override
    public String toString() {
        return super.toString() + " course = " + course ;
    }    
}

标签: javaarraylist

解决方案


推荐阅读