泛型语法
来源:8-11 泛型(上)

红邮筒
2018-12-04
老师,“linkedlist.of(1,2,3)”,"linkedlist.<> 函数()"这是什么语法,网上也搜不到具体的解释,还是自己定义的?
1回答
-
<>里的东西在Java 1.7以后是可以省略的,比如List<Integer> list = new LinkedList<>(),只要编译器能推断的出来。我的技巧是一开始先写空的<>,如果编译出错,那么我们再把<>里面的内容填上。
linkedlist.<>函数(),这个就是调用泛型函数的方法。举个例子:
class Processor {
public <T> void process(T data, Writer<T> writer) {...}
}
这里我们要求data的类型和writer能够写的类型是相同的。我们可以这样调:
processor.process(5, new IntWriter());
当然IntWriter一定是implements Writer<Integer>
但有些特殊的情况,比如我视频里具Equals例子,编译器认不出来这个T到底是啥,那么我们也可以显示告诉编译器,上面这行也能写成:
processor.<Integer>process(5, new IntWriter());
另一个linkedlist.of(1,2,3),这是一个static函数,我们可以参考Google Guava库:https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/ImmutableList.java#L102
这个函数的用法就是:List<Integer> list = ImmutableList.of(1, 2);
012018-12-07
相似问题