I am able to insert duplicate entries in TreeSet. How to overcome this

后端 未结 3 1574
猫巷女王i
猫巷女王i 2021-01-14 16:15

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

相关标签:
3条回答
  • 2021-01-14 16:40

    The problem is here:

    ((Employee)emp).employeeName== this.employeeName
    

    You must compare Strings 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 a Comparator 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.

    0 讨论(0)
  • 2021-01-14 16:43

    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);
    }
    
    0 讨论(0)
  • 2021-01-14 16:55

    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)
    
    0 讨论(0)
提交回复
热议问题