集合remove()方法相關問題

學習集合的過程中,了解到一個有關於remove()方法的有關特性,特此記錄

首先remove方法的格式:

collection.remove(Object o);

這是指對集合collection內的某對應的元素o進行移除操作。

學習過程中,經過老師的提問,當我們將o換成一個匿名對象,是否也可以經過比較進行刪除該元素?示例如下(創建一個Student類,類中只有age和name變數):

Collection collection = new ArrayList();
Student s1 = new Student(10,"a");
Student s2 = new Student(12,"b");
Student s3 = new Student(13,"c");

//添加三個元素
collection.add(s1);
collection.add(s2);
collection.add(s3);

//刪除前
System.out.println(collection.size());
for (Object o: collection) {
     Student s = (Student) o;
     System.out.println(s.getAge() + s.getName());
}
collection.remove(new Student(10,"a"));
//刪除後
System.out.println(collection.size());
for (Object o: collection) {
    Student s = (Student) o;
    System.out.println(s.getAge() + s.getName());
}

當運行這段程式碼後,結果為:

image-20220208221535151

也就是說,這個沒法這樣刪除掉,那非要這麼用可以做到嗎

答案是可以的,這個涉及到remove方法中的源碼(但是我很菜所以直接寫上老師的回答,在此記錄一下QWQ):

remove方法內的大致邏輯是,比較形參和集合內元素是否相等,這種相等不僅要元素內容相等,並且地址也要相同,其使用的方法為equals()方法進行的判斷。

那麼使用equals()判斷就很簡單了,在Student類中重寫equals方法,讓他不需要判斷地址就可以了

@Override
public boolean equals(Object o) {
    if (this == o) 
        return true;
    if (o == null || getClass() != o.getClass()) 
        return false;
    Student student = (Student) o;
    return age == student.age && Objects.equals(name, student.name);
    }

當重寫之後,針對remove方法中使用的equals方法也就重寫了,這樣就可以不必比較地址,以同樣的程式碼運行,結果為:

image-20220208222033112

10 a的結果少了,說明刪除成功。


這個解釋不夠完美,沒有涉及很底層,因為在我現在的認知里,介面的方法是沒有方法體的,我不理解沒有方法體如何實現方法,所以這裡只是先做個筆記,如果有懂的大佬,可以指導我一下嗎謝謝QWQ

再者,就是讚賞一下idea真是方便鴨,重寫equals方法直接快捷點幾個按鍵就直接幫我生成了!好感+1