Visitor :

May 4, 2009

Implementing equals method of collections classes


Let us supposed to have ArrayList, to sort, binary search, remove you need to know equal. This is connected to implement equals method of Object.
Just you have implement equals, it is very easy to manipulate Collections. Internally in Collections classes, there are many usage of equals methods.




public class MetaConnectionData {
private String project;

private String subDomain;

private String port;

public MetaConnectionData(String _project, String _subDomain, String _port) {
this.project = _project;
this.subDomain = _subDomain;
this.port = _port;
}

public String getProject() {
return project;
}

public void setProject(String project) {
this.project = project;
}

public String getSubDomain() {
return subDomain;
}

public void setSubDomain(String subDomain) {
this.subDomain = subDomain;
}

public String getPort() {
return port;
}

public void setPort(String port) {
this.port = port;
}

public boolean equals(final Object other) {
if (this == other) {
return true;
} else if ((other != null) && (other.getClass() == getClass())) {
final MetaConnectionData otherData = (MetaConnectionData) other;
if (otherData.getPort().equals(port)
&& otherData.getProject().equals(project)
&& otherData.getSubDomain().equals(subDomain)) {
return true;
}
}
return false;
}
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
public int hashCode() {
return toString().hashCode();
}
}


No comments:

Post a Comment