In Java, if you call the Remove method in ArrayList, which essentially compares the object to remove with each object in the list, the method of comparison is to call the Equals method in object, essentially comparing the memory addresses of 2 objects. As the following code: we want to delete an employee object, so we are new to the original employee object content exactly the same object, obviously this is not removed, Because calling the Remove method is actually invoking the Equals method in employee, because the employee class does not override the Equals method of object, the call is the Equals method of object, which is essentially a memory address that compares 2 objects. is obviously not the same.
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");
The Equals method
Emplist.remove (EMP11) of the EMP is invoked;
Iterator it = Emplist.iterator ();
while (It.hasnext ()) {
Employee EMP = (employee) it.next ();
System.out.println ("Name:" +emp.getname ());}}}
To implement the above code, we will override the Equals method of object in the Employee class, as follows:
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;
The 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;
The public void Setbirthday (Date birthday) {this.birthday = birthday;
public float getsalary () {return salary;
public void Setsalary (float salary) {this.salary = salary;
@Override public 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;}
}
}
In this way, the overridden Equals method is essentially a comparison of the contents of the employee object, as is the implementation of the Contains method in ArrayList.