Sebastien Sebastien - 1 year ago 113
Java Question

Why does String equals() return false (custom Comparator involved)?

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

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? Is it some kind of pointer to the String object data?

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

Because of the previously mentioned problem, combinations contains duplicates.

When I set NO custom Comparator for this TreeSet, there is no duplicate any more (that's what I want) but it is sorted alphabetically which is normal but not my purpose.

Answer Source

If what you're trying to do is sort by length but discard duplicates, the following should work.

import java.util.TreeSet;
import java.util.Comparator;
import java.util.Arrays;

public class MyComparator implements Comparator<String> {
    public int compare(String s1, String s2) {
        int s1Length = s1.length();
        int s2Length = s2.length();
        if (s1Length == s2Length) {
             return s1.compareTo(s2);
        else {
              return s1Length - s2Length;


    public static void main(String[] args) {
    String[] strings = {"Hello", "Hello", "longer", "1", "477727357235", "hello"};

    TreeSet<String> set = new TreeSet<String>(new MyComparator());

        // Won't be duplicates with substrings
        String s = "Hello World";
        for (int i = 0; i <= s.length(); i++) {
            String s1 = s.substring(0, i);
        // Still won't be a duplicate, even if we make a copy of the string.
        set.add(new String(s));


Output: [, 1, H, He, Hel, Hell, Hello, hello, Hello , longer, Hello W, Hello Wo, Hello Wor, Hello Worl, Hello World, 477727357235]