Search code examples
javabinaryequalsbitwise-and

String.equals() to change with bitwise AND on binary numbers


In Java, working with binary strings (e.g. "00010010", zeroes are added in the beginning when creating these binary strings for the purpose of my program). I have the function

private static boolean isJinSuperSets(String J, List<String> superSets) {

    for (String superJ : superSets)
        if (superJ.equals(J)) return true;

    return false;
}

that checks if a binary string J is contained in the list of binary strings superSets.

I use equals() on the String object but I would like to speed up this code by converting binary strings to binary numbers and doing bitwise operation AND to see if they are equal.

Could you please give me a few tricks on how to accomplish that?


Solution

  • Here for int:

    for (String superJ : superSets)
            return Integer.valueOf(superJ,2) == Integer.valueOf(J,2);
    }
    

    You have to test with benchmarks (take care first time is always slower) for speed.

    The best way to optimize if J is more than once used : have J2 as Integer somewhere and test on it.