Search code examples
javaarrayssearchstore

Store and find if a certain array is already stored


My program checks multiple boolean arrays (length 30 each) and I would like to know if I already checked that array. I thought the best way to handle this problem would be to store all the arrays and search for the new array in the set of all the arrays but I don't know what structure I should use. At first, I though hashtable would be the best but it looks like I can't use them with arrays. I looked for set and list but I have no clue what to use !

Edit/clarification: Hey it's my first question here and I'm surprised how many answers I received, thanks a lot ! Lot of people says they are unsure about what exactly I'm looking for so I'll try to clarify:

I have multiple boolean arrays of length 30 where the order is important ( order of elements in the array).

I receive one array at a time and I want to check if I already received the same array (same element, same order). I don't need to store them( I don't need any index, I don't want to know how many arrays I received), don't need anything except to know if I already received the array.


Solution

  • A boolean array is basically a list of bits. Since array size is 30, and an int is a 32-bit value, you can convert the array into an int. With a long you could support arrays up to 64 in size.

    So, first convert your array to an int:

    private static int toBits(boolean[] array) {
        if (array.length > 32)
            throw new IllegalArgumentException("Array too large: " + array.length);
        int bits = 0;
        for (int i = 0; i < array.length; i++)
            if (array[i])
                bits |= 1 << i;
        return bits;
    }
    

    Then keep track using a Set<Integer>:

    private Set<Integer> alreadySeen = new HashSet<>();
    
    private boolean firstTime(boolean[] array) {
        return ! this.alreadySeen.add(toBits(array));
    }
    

    This provides a very fast and low-memory implementation that can handle lots of boolean arrays.