What does it mean for a collection to be “backed by” another? Give an example of when this property is useful.

Solution:

If a collection backs another, it means that changes in one are reflected in the other and vice-versa.

For example, suppose we wanted to create a whitelist function that removes invalid keys from a Map. This is made far easier with Map.keySet, which returns a set of keys that is backed by the original map. When we remove keys from the key set, they are also removed from the backing map:

        public static <K, V> Map<K, V> whitelist(Map<K, V> map, K... allowedKeys) {
            Map<K, V> copy = new HashMap<>(map);
            copy.keySet().retainAll(asList(allowedKeys));
            return copy;
        }

retainAll writes through to the backing map, and allows us to easily implement something that would otherwise require iterating over the entries in the input map, comparing them against allowedKey, etcetera.

Note, it is important to consult the documentation of the backing collection to see which modifications will successfully write through. In the example above, map.keySet().add(value) would fail, because we cannot add a key to the backing map without a value.

0 answers