Check if two Bundle objects are equal in Android?
I have tested Sam's answer and it contains a flaw. Plus I am loving Kotlin at the moment, so here is my version.
- Again the keys sets need to be the same size
- The key sets need to have the same values
- If both values are
Bundle
then test recursively. - Otherwise test values for equality (don't retest bundles)
Code:
fun equalBundles(one: Bundle, two: Bundle): Boolean {
if (one.size() != two.size())
return false
if (!one.keySet().containsAll(two.keySet()))
return false
for (key in one.keySet()) {
val valueOne = one.get(key)
val valueTwo = two.get(key)
if (valueOne is Bundle && valueTwo is Bundle) {
if (!equalBundles(valueOne , valueTwo)) return false
} else if (valueOne != valueTwo) return false
}
return true
}
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 benull
, make sure that both values arenull
and that the key actually exists intwo
- 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;
}