1

When adding two Order objects to a TreeSet I see that the first is added, but the second is ignored. The implementation of the Order.equals method is shown below. Both the objects definitely have different orderIds, but more importantly I placed a break point within the equals method and it did not get hit?!

My question is why would the second Order was added to the TreeSet. The only reason I can think of is that it had the same orderId, hence it would have been ignored, but this is definitely not the case.

private final long orderId;

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Order other = (Order) obj;
    if (orderId != other.orderId)
        return false;
    return true;
}
Zong
  • 6,160
  • 5
  • 32
  • 46
newlogic
  • 807
  • 8
  • 25

2 Answers2

2

TreeSet uses the object's implemented Comparable<Order> or by a provided Comparator<Order> to determine equivalence.

Glenn Lane
  • 3,892
  • 17
  • 31
0

From the Java documentation, TreeSet can also use the natural ordering, depending which constructor is used. Your way to override the equals method looks fine.

Juto
  • 1,246
  • 1
  • 13
  • 24