Search code examples
javahashmapstringbuilder

Why does HashMap allow duplicates and StringBuilder does not reverse properly?


HashMap should not allow duplicates, while StringBuilder.reverse() does not work properly. Why?

String s = "abba";
static int myMethod(String s) {
        int counter = 0;
        Map<StringBuilder, StringBuilder> map = new HashMap<>();
        for (int j = 0; j <= s.length(); j++) {
            for (int i = j + 1; i <= s.length(); i++) {
                StringBuilder sb = new StringBuilder(s.substring(j, i));
                map.put(sb, sb.reverse());
            }
        }
        System.out.println("map " + map);
        return counter;
    }

Output:

map {bba=bba, ba=ba, b=b, a=a, a=a, ab=ab, abb=abb, abba=abba, b=b, bb=bb}


Solution

  • You shouldn't store StringBuilder in the HashMap, because unlike String it does not implement equals() and hashCode() methods based on its content (it inherits them from Object). Two different instances of a StringBuilder can never be equal. In order for the program to function properly and prevent duplicates, store String instead:

    String s = "abba";
    int counter = 0;
    Map<String, String> map = new HashMap<>();
    for (int j = 0; j <= s.length(); j++) {
         for (int i = j + 1; i <= s.length(); i++) {
              StringBuilder sb = new StringBuilder(s.substring(j, i));
              StringBuilder reverse = sb.reverse();
              map.put(s.substring(j, i), reverse.toString());
         }
    }
    System.out.println("map " + map);
    

    Output:

    map {abb=bba, bb=bb, bba=abb, a=a, ab=ba, b=b, abba=abba, ba=ab}