Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Question on TreeSet contains(...) method

875960Jul 16 2011 — edited Jul 18 2011
Hey guys,

The contains method returns true even if I do not override equals(Object o), which is kinda contradictory to what API says about this method. It seems that it returns true as long as I have a meaningful compareTo overridden.

For example:

class Dog implements Comparable<Dog> {
String name;
public Dog(String n) { name = n; }
public int compareTo(Dog d) { return name.compareTo(d.name); }
}

In main:
Set<Dog> s = new TreeSet<Dog>();
Dog d1 = new Dog("aaa");
Dog d2 = new Dog("aaa");

s.add(d1);

System.out.println(s.contains(d2)); // returns true
System.out.println(d1.equals(d2)); // return false because I do not have equals overridden.

According to the following API statement, however, should contains return false in this case?

Thanks,

Bohan


From API doc:

"contains

public boolean contains(Object o)

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e))."
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 15 2011
Added on Jul 16 2011
12 comments
980 views