Search code examples
androidbundle

Check if two Bundle objects are equal in Android?


I would like to check if two bundles are equal, is there any way to do that instead of checking them key by key?


Solution

  • Here is one way to test if two Bundles are the same:

    • Check their sizes, don't bother if they're not equal
    • If both values are Bundle objects use recursion
    • Because a value for a key in one can be null, make sure that both values are null and that the key actually exists in two
    • Finally compare the matching keys' values

    Code:

    public boolean equalBundles(Bundle one, Bundle two) {
        if(one.size() != two.size())
            return false;
    
        Set<String> setOne = new HashSet<>(one.keySet());
        setOne.addAll(two.keySet());
        Object valueOne;
        Object valueTwo;
    
        for(String key : setOne) {
            if (!one.containsKey(key) || !two.containsKey(key))
                return false;
    
            valueOne = one.get(key);
            valueTwo = two.get(key);
            if(valueOne instanceof Bundle && valueTwo instanceof Bundle && 
                    !equalBundles((Bundle) valueOne, (Bundle) valueTwo)) {
                return false;
            }
            else if(valueOne == null) {
                if(valueTwo != null)
                    return false;
            }
            else if(!valueOne.equals(valueTwo))
                return false;
        }
    
        return true;
    }