When a collection contains
object of user defined class:-
contains()
of collection classes internally used equals() method to compare objects
provided by Object class, equals()’s method of Object class compare value of
reference variable not content of object. So, must override equals() method in
own class to provide content by comparison.
- Using ArrayList or LinkedList simply override equals() method
public class Emp {
String name;
String job;
int sal;
public Emp(String n, String j, int s) {
name = n;
job = j;
sal = s;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
public boolean equals(Object o){
Emp e=(Emp)o;
return
(name.equals(e.name))&&(job.equals(e.job))&& sal==e.sal;
}
}
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList list=new ArrayList();
list.add(new
Emp("naveen","SE",18000));
list.add(new
Emp("raj","SE",15000));
list.add(new
Emp("dinesh","Analyst",18000));
Emp e=new
Emp("raj","SE",15000);
System.out.println(list.contains(e));
}
}
- Using HahSet or HashMap must override
hashCode() and equals() both.
To store object of user define class in hashing
based collection:
- Must
override hashcode() method in such a manner that two objects with same
content has same has code.
- Must
override equals() method in such a manner compare content of the object
public class Emp {
String name;
String job;
int sal;
public Emp(String n, String j, int s) {
name = n;
job = j;
sal = s;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
@Override
public boolean
equals(Object o){
Emp e=(Emp)o;
return
(name.equals(e.name))&&(job.equals(e.job))&& sal==e.sal;
}
@Override
public int hashCode() {
return
name.hashCode()+job.hashCode()+sal;
}
}
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
HashSet list=new HashSet();
list.add(new
Emp("naveen","SE",18000));
list.add(new
Emp("raj","SE",15000));
list.add(new
Emp("dinesh","Analyst",18000));
Emp e=new
Emp("raj","SE",15000);
System.out.println(list.contains(e));
}
}
- Using TreeSet or TreeMap
Tree Base collection internally uses some method to
comparing element for sorting. This comparison logic is provided either using
java.lang.Comparable interface (default) or java.util.Comparator interface (by
specifying in constructor e.g. TreeMap(Comparator)).
So, must override this method.(discuss in detail in
earlier session)
No comments:
Post a Comment