Search code examples
javasetcontainsstringbuilder

Does Java Set<String> contains() check for existence of StringBuilder?


Does Java Set contains() know how to check for the existence of StringBuilder?

I am running this problem in Leetcode. "Find Unique Binary String". Note this Question is not about Solving the Leetcode, but understanding why an issue occurs. https://leetcode.com/problems/find-unique-binary-string/description/

Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.

nums = ["00","01"]

Code Output "00"

Expected Answers Choice "10"

Problem:

This code fails at !currentResults.contains(currentString) where currentString is "00" ,when the number exists in the Set.

Changing it to !currentResults.contains(currentString.toString())) will make it succeed. I am trying to understand reason behind this.

Code:

List<String> results = new ArrayList<>();
Set<String> currentResults = new HashSet<>();
String finalString;
int numsLength;

public String findDifferentBinaryString(String[] nums) {
    
    for (String data: nums) {
        currentResults.add(data);
    }
    if (nums.length == 0) {
        return "";
    }
    numsLength = nums.length;
    getDFS(nums, new StringBuilder(""));
    return finalString;
}

public void getDFS(String[] nums, StringBuilder currentString) {
    if (finalString != null ) {
        return;
    }

    if (currentString.length() == numsLength && !currentResults.contains(currentString)) {
        finalString = currentString.toString();
        return;
    }

    if (currentString.length() == numsLength) return;

    for (int i = 0; i <= 1; i++) {
        currentString.append(String.valueOf(i));
        getDFS(nums,currentString);
        currentString.deleteCharAt(currentString.length() - 1);
    }
}

Solution

  • Does Java Set Contains() know how to check for existence of Stringbuilder?

    No, Set.contains(Object o) checks for the existence of an Object that equals.

    Quoting:

    Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

    This means that a StringBuilder type will not satisfy the .equals() clause because it will call String.equals() and StringBuilder will not satisfy a true condition without explicitly calling .toString() first.

    There are other cases in the Java language where .toString() is implicitly called, but the .equals() operator for String is not one of those cases.

    (comment) I was hoping it would match set type and give a warning if String type does not match with StringBuilder

    Some code editors -- such as IntelliJ -- will try to warn about this, see attached picture:

    enter image description here