Understanding TreeSet when compareto returns 0

我是研究僧i 提交于 2019-11-30 23:38:58
meskobalazs

As java.util.TreeSet says:

a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal

Kudos to @Jon Skeet.

That is because TreeSet uses compareTo (or Comparator.compare) to test whether two elements are equal. This is what the docs say about it.

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

vels4j

Since you have compared only first name in compareTo method, you need

 @Override
public int compareTo(Student student) {
    int comp = this.firstName.compareTo(student.firstName);
    if(comp==0) return this.lastName.compareTo(student.lastName);
    return comp;
}

when compareTo returns 0, treeSet assumes that its duplicate.

Well, your treeset key values are "A1","B1","A1","A2". Even though you are not overriding equals and hashcode still the default hashcode for "A1" will be same and hence the treeset will consider this key as duplicate key so you will not be able to enter "A1","B2"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!