I’m using compareTo() in a doubly-linked-list to compare a code and a read string, and can’t figure out why it isn’t working. It’s a lot of code involved, but I don’t want to make you guys read through it all, so I’ll try to post just what is relevant and hope it’s enough.
This is the line of code. I know it’s incomplete, but everything else is working properly.
if(p.getCode().compareTo(str)==0){
And they ARE equal. I printed them out the right before this comparison happens and they are the same.
I know not much has been given, and I’m kind of asking you to trust me that they really are equal, but it’s to save you time. I’m wondering whether there is some sort of special rules I should know about regarding compareTo() I am missing…
Thanks.
compareTois provided by the Comparable interface. There is no language enforced requirement thatComparable.compareToreturn0whenObject.equalsreturnstrue. That is, two instances of an object may be completely identical and an implementation ofComparator.compareTodoes not have to return0.Assuming that
p.getCodereturns aStringand the argumentstris aString, then the implementation ofStringdoes ensure thatequalsandcompareToare consistent.So there are other possibilities:
Comparatormust be used.