java中的ArrayList類中的remove方法

來源:互聯網
上載者:User

在java中如果調用了ArrayList中的remove方法,其本質上是將要remove的對象與list中的每一個對象進行比較,比較的方法是調用Object中的equals方法,本質上是比較2個對象的記憶體位址是否一樣。如下面的代碼:我們想刪除一個Employee對象,所以我們就new了一個和原來Employee對象內容完全一樣的對象,很顯然這樣是不能remove掉的,因為調用remove方法的時候其實是調用Employee中的equals方法,因為Employee類並沒有重寫Object的equals方法,所以調用的還是Object的equals方法,本質上是比較2個對象的記憶體位址,顯然是不一樣的。

 

import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class ArrayListTest4 {/** * @param args */public static void main(String[] args) {List<Employee> empList = new ArrayList<Employee>();empList.add(new Employee(1,"jack"));Employee emp1 = new Employee(2,"tom");empList.add(emp1);//jack Employee emp11 = new Employee(1,"jack");//調用的是emp的equals方法empList.remove(emp11);Iterator it = empList.iterator();while(it.hasNext()){Employee emp = (Employee)it.next();System.out.println("name:"+emp.getName());}}}

如果要實現上面的代碼,我們就要在Employee類中重寫Object的equals方法,代碼如下:
import java.util.Date;public class Employee {private int empID;private String name;private Date birthday =  new Date();private float salary = 3000.0f;public Employee(int empID, String name) {this.empID = empID;this.name = name;}public int getEmpID() {return empID;}public void setEmpID(int empID) {this.empID = empID;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public float getSalary() {return salary;}public void setSalary(float salary) {this.salary = salary;}@Overridepublic boolean equals(Object obj) {boolean flag = obj instanceof Employee;if(flag == false){return false;}Employee emp = (Employee)obj;if(this.getEmpID()==emp.getEmpID() && this.getName().equals(emp.getName())){return true;}else {return false;}}}
這樣的話就能實現了,重寫後的equals方法實質上是比較Employee對象中的內容,ArrayList中的contains方法的實現也是這樣的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.