Treeset.contains() problem

后端 未结 3 1136
甜味超标
甜味超标 2021-02-14 13:57

So I\'ve been struggling with a problem for a while now, figured I might as well ask for help here.

I\'m adding Ticket objects to a TreeSet, Ticket implements Comparable

3条回答
  •  一个人的身影
    2021-02-14 14:50

    Firstly, if you are using a TreeSet, the actual behavior of your hashCode methods won't affect the results. TreeSet does not rely on hashing.

    Really we need to see more code; e.g. the actual implementations of the equals and compareTo methods, and the code that instantiates the TreeSet.

    However, if I was to guess, it would be that you have overloaded the equals method by declaring it with the signature boolean equals(Ticket other). That would lead to the behavior that you are seeing. To get the required behavior, you must override the method; e.g.

    @Override
    public boolean equals(Object other) { ...
    

    (It is a good idea to put in the @Override annotation to make it clear that the method overrides a method in the superclass, or implements a method in an interface. If your method isn't actually an override, then you'll get a compilation error ... which would be a good thing.)

    EDIT

    Based on the code that you have added to the question, the problem is not overload vs override. (As I said, I was only guessing ...)

    It is most likely that the compareTo and equals are incorrect. It is still not entirely clear exactly where the bug is because the semantics of both methods depends on the compareTo and equals methods of the Boeking class.

    The first if statement of the Ticket.compareTo looks highly suspicious. It looks like the return 1; could cause t1.compareTo(t2) and t2.compareTo(t1) to both return 1 for some tickets t1 and t2 ... and that would definitely be wrong.

提交回复
热议问题