Careful about what you put in TreeSet

TreeSet works great when you use classes that come with JDK like String, Integer etc. But when you use a custom class that implements Comparable in TreeSet, you’ll have to be careful about the implimentation for compareTo. TreeSet uses the equality defined by the ‘compareTo’ method rather than the ‘equals’ provided by Object. In other words, for a TreeSet two objects are equal if the compareTo method returns a zero.

Issue:

Consider this class

class Document implements Comparable {
	String docID; int count;
	public int compareTo(Object obj){
		Document param=(Document)obj;
		return param.count-count;
	}
}

I was trying to add multiple Document instances to the set that had the count initialized to 1. As a result only the first one got added.

The fix:

public int compareTo(Object obj)
{
	Document param=(Document)obj;
	int tmp= param.count-count;
	if (tmp==0) return -1;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: