Hello,
I built a very simple custom Comparator, that I use with a TreeSet in order to sort Strings by length in that TreeSet.
I'm having trouble finding the reason why (s1.equals(s2))
returns false even when the two strings s1 and s2 contain the same value...
Eclipse "variables view" shows the letters are the same in both strings, but the "id" is different, I guess that's why equals returns False. By the way what is that id=" " representing ? some kind of pointer to the String object data ?
Here is the screenshot: http://yfrog.com/2rvariablesproblemj
public class MyComparator implements Comparator<String> {
public int compare(String s1, String s2) {
if(s1.length()<s2.length()) return -1;
else if (s1.length()>s2.length()) return 1;
return 0;
else if (s1.equals(s2)) return 0; //?? ALWAYS RETURNS FALSE
else if (s1.toString().equals(s2.toString()))//SAME PROBLEM HERE (test)
else return -1;
}
public boolean equals(String s) {
if (this.equals(s)) return true;
else return false;
}
}
Now here is where I use this custom Comparator:
combinations = new TreeSet<String>(new MyComparator());
I fill combinations with several Strings, built with the substring() method. Because of the previously mentioned problem, combinations contains duplicates.
When I set NO custom Comparator for this TreeSet, there is no duplicate anymore (that's what I want) but it is sorted alphabetically which is normal but not my purpose.
Thanks in advance for your help on understanding the WHY of this...
Sébastien