I have a class called Employee which has employeeName
and employeeId
as its member variables.I am creating new Employee objects and then adding it
The problem is here:
((Employee)emp).employeeName== this.employeeName
You must compare String
s using equals
method:
((Employee)emp).employeeName.equals(this.employeeName)
Refer to How do I compare strings in Java?
Also, since you're overriding equals
method, it would be good if you override hashCode
method as well, as stated in Object#equals contract:
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Additional: Since you're using TreeSet
, it will use the compareTo
method instead of the equals
and hashCode
methods. This is because TreeSet
implements SortedSet
interface. Refer to SortedSet javadoc (emphasis mine):
A Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering(i.e. implementing
Comparable<T>
), or by aComparator
typically provided at sorted set creation time.
You should implement this method in the accordingly to your needs:
public int compareTo(Employee emp) {
if (this.employeeName.equals(emp.employeeName)) {
return 0;
}
//removed the comparison by subtraction since it will behave wrongly on int overflow
return new Integer(this.employeeId).compareTo(emp.employeeId);
}
Since you're comparing Strings, I would recommend using StringUtils class from Apache Commons Lang that provides helper methods to avoid null
checks and others.
you should compare string
not with ==, but with equals()
method, and also you should override your compareTo
method to compare with employeeName
not with employeeId
, if you want it in that way.
(Employee)emp).employeeName.equals(this.employeeName)
and
public int compareTo(Employee emp) {
return (this.employeeName-emp.employeeName);
}
The way you are comparing string is wrong. See How to compare 2 Strings in Java
(Employee)emp).employeeName== this.employeeName
should be
(Employee)emp).employeeName.equals(this.employeeName)