學習集合的程序中,了解到一個有關于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());
}
當運行這段代碼后,結果為:

也就是說,這個沒法這樣洗掉掉,那非要這么用可以做到嗎
答案是可以的,這個涉及到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方法也就重寫了,這樣就可以不必比較地址,以同樣的代碼運行,結果為:

10 a的結果少了,說明洗掉成功,
這個解釋不夠完美,沒有涉及很底層,因為在我現在的認知里,介面的方法是沒有方法體的,我不理解沒有方法體如何實作方法,所以這里只是先做個筆記,如果有懂的大佬,可以指導我一下嗎謝謝QWQ
再者,就是贊賞一下idea真是方便鴨,重寫equals方法直接快捷點幾個按鍵就直接幫我生成了!好感+1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/423542.html
標籤:其他
