Let there be an employee class that contains main job and salary. This class also contains a parameterised constructor and a display method.
import java.util.*;
class Emp
{
String name, job;
int salary;
Emp(String n, String j, int s)
{
name = n;
job = j;
salary = s;
}
public void display()
{
System.out.println(name + "t"+job+"t" + salary);
}
public boolean equals(Object o)
{
Emp e = (Emp)o;
return this.name.equals(e.name) && this.job.equals(e.job) && this.salary == e.salary;
}
}
class TestEmp
{
public static void main(String args[])
{
ArrayList list = new ArrayList();
list.add(new Emp("Amit","Manager",25000));
list.add(new Emp("Sumit","Trainer",35000));
list.add(new Emp("Vinit","Accountant",20000));
list.add(new Emp("Rohit","Trainee",10000));
System.out.println("The number of records in list : "+list.size());
Iterator itr = list.iterator();
while(itr.hasNext())
{
Emp e = (Emp)itr.next();
e.display();
}
Emp e1 = new Emp("Amit", "Manager",25000);
System.out.println("Removing following record from the list");
e1.display();
list.remove(e1);
System.out.println("Total number of record after removal in list : "+list.size());
Emp e2 = new Emp("Rohit", "Trainee", 20000);
System.out.println("Searching following record in list.");
e2.display();
System.out.println("Result of search is : "+list.contains(e2));
}
}
Whenever an element is searched in a list, an exastive search is intiated by the contains method using equals() method taht element to be searched is compared for equality with each list element these comparision are made until element is found or all the elements are compared. Success or failure of a search operation in a list in dynamic depends on the implements of equals method.
Note : Defualt implementation of equals method in object class compares the value of reference not the content of an object.
In order to successfully search object of user defined class in a list, equals method must be overridden in the lcass to facilitate content wise comparision.
0 Comments:
Post a Comment