简体   繁体   中英

Why is it acceptable to omit the generic type parameter here?

In the following snippet:

public class IDMapBase<T> extends HashMap<DeviceID, T> {
    public Map<DeviceID, T> filterMap(Set<DeviceID> neededIDs) {
        return entrySet().stream()
            .filter(e -> neededIDs.contains(e.getKey()))
            .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    }
}

Why is it OK to simply say Entry::getXX instead of Entry<DeviceID, T>>::getXX ? I thought that (Map.)Entry would default to Entry<Object, Object> , which is not usable as an entry of a Map<DeviceID, T> .

Your input parameter has a enough type information for the compiler to infer all the intermediate generic types.

It can figure that "what comes in" and "what comes out" ... and the "steps in between" match up.

Example: the first call is entrySet() ; so probably the surrounding class is a Map with defined K, V. So the compiler knows that it is dealing with some EntrySet<K,V> ... probably matching up with the generic type found on neededIDs .

And so on ... if you are interested in "inferring" the types yourself; I would suggest that you start by decomposing those fluently chained method invocations. One by one; figure what they return, and what you can know about the result types of each operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM