Explain me what does it mean for a collection to be “backed by” another? Give an example of when this property is useful?
Submitted by: MuhammadIf 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.
Submitted by: Muhammad
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.
Submitted by: Muhammad
Read Online Java Software Engineer Job Interview Questions And Answers
Top Java Software Engineer Questions
☺ | Do you know how threadsafe is enum in Java? |
☺ | Explain me what is a good usecase of calling System.gc()? |
☺ | Explain me why doesn’t the following code generate a NullPointerException even when the instance is null? |
☺ | Do you know what is the advantage of generic collection? |
☺ | Tell us what do you mean by aggregation? |
Top Java Programming Language Categories
☺ | Core Java Interview Questions. |
☺ | Hibernate Interview Questions. |
☺ | Advanced Java Interview Questions. |
☺ | IBM WebSphere Interview Questions. |
☺ | Spring Framework Interview Questions. |