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