I am doing the following
class RuleObject implements Comparable{
@Override
public String toString() {
return "RuleObject [colIndex=" + colIndex + ", probability="
+ probability + ", rowIndex=" + rowIndex + ", rule=" + rule
+ "]";
}
String rule;
double probability;
int rowIndex;
int colIndex;
public RuleObject(String rule, double probability) {
this.rule = rule;
this.probability = probability;
}
@Override
public int compareTo(Object o) {
RuleObject ruleObj = (RuleObject)o;
System.out.println(ruleObj);
System.out.println("---------------");
System.out.println(this);
if(ruleObj.probability > probability)
return 1;
else if(ruleObj.probability < probability)
return -1;
else{
if(ruleObj.colIndex == this.colIndex && ruleObj.rowIndex == this.rowIndex && ruleObj.probability == this.probability && ruleObj.rule.equals(this.rule))
return 0;
}
return 1;
}
}
And I have a TreeSet containing elements of RuleObject.
I am trying to do the following :
System.out.println(sortedHeap.size());
RuleObject ruleObj = sortedHeap.first();
sortedHeap.remove(ruleObj);
System.out.println(sortedHeap.size());
I can see that the size of set remains same. I am not able to understand why is it not being deleted.
Also while deleting I could see compareTo method is called. But it is called for only 3 object whereas in set there are 8 objects.
Thanks
Look at the specification for
remove:Your problem is that
RuleObjectdoes not@Override equals(Object other). You need to do that, and of course, with that you also need to@Override hashCode().Also, the reason why
compareTois being called fewer times than the number of elements is because it’s supposed to be aO(log N)operation; that’s the whole purpose of usingTreeSet. If you have 1024 elements, you can expectcompareToto be called no more than 10 times.As Vlad points out, your comparator is broken. Specifically, the last statement
return 1;breaks it. You should expand the equalprobabilitycase to return -1, 0, +1 depending on the other fields.