简体   繁体   English

为什么在这里省略泛型类型参数是可以接受的?

[英]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 ? 为什么只说Entry::getXX而不是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> . 我认为(Map.)Entry将默认为Entry<Object, Object> ,这不能用作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() ; 示例:第一个调用是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 . 因此周围的类可能是具有定义的K,V的Map。因此,编译器知道它正在处理某些EntrySet<K,V> ...可能与在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. 弄清楚它们返回什么,以及您可以了解每个操作的结果类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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