问题描述
我发现了一种不寻常的"通用语法,例如:
I found a 'unusual' generic syntax such as:
Arrays.<String>asList(...);
Collections.<String>emptyList();
显然,这些方法的结果是通用的.这样的语法用于类型检查吗? Object
数组不能是Arrays.<String>asList(...)
的参数.
Obviously, the results of the methods are generic. Is such syntax for type checking? An Object
array cannot be an argument to Arrays.<String>asList(...)
.
推荐答案
<typearg>methodname
是为通用方法显式指定类型实参的语法
<typearg>methodname
is the syntax for explicitly specifying the type argument for a generic method
使用泛型类时,通常必须指定类型参数(例如String
):
When you use a generic class, you usually have to specify the type argument (e.g. String
):
ArrayList<String> list = new ArrayList<String>();
使用通用方法,通常不会传递类型参数:
With a generic method, you don't usually pass a type argument:
public static <T> void foo(T param) { }
...
String s = ...;
MyClass.foo(s);
您不会注意到我们没有在哪里做代码来明确指定我们想要的String
版本的foo
,即没有指定明确的类型实参<String>
,就像我们在使用泛型类时看到的那样().
You'll notice no where did we did the code explicitly specify we want the String
version of foo
, i.e. there was no explicit type argument <String>
specified like we saw when using a generic class (List<String>
).
编译器正在做一些编译器魔术,以根据上下文推断泛型类型参数.这是一件了不起的事情,非常强大.
The compiler is doing some compiler magic to infer the generic type argument based on context. This is a great thing and very powerful.
但是,有时编译器无法自动推断类型参数:
However, occassionally the compiler can't infer the type arguments automatically:
public static <T> void bar() { T myLocalVar = ...; ... }
MyClass.bar();
我们试图调用bar
的什么具体版本,即此调用的类型参数是什么?不知道?好吧,编译器也没有.我们必须像使用泛型类时通常那样明确声明类型参数:
What concrete version of bar
are we trying to invoke, i.e. what is the type argument for this call? Dunno? Well, the compiler doesn't either. We have to explicitly state the type argument, just like we normally do when using a generic class:
MyClass.<String>bar();
另请参阅:
- http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedMethods .html#FAQ002
- 那里还有很多其他好东西 http://www. angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
- http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedMethods.html#FAQ002
- Lots of other good stuff there http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
此外:可能值得一提的是,Java 7将添加所谓的菱形运算符,以使我们现在也可以使用通用类时让编译器来推断类型参数:
Aside: it may be worth mentioning that the Java 7 will be adding the so-called diamond operator to allow us to have the compiler to infer the type arguments when using generic classes now too:
ArrayList<String> list = new ArrayList<String>();
成为
ArrayList<String> list = new ArrayList<>();
这篇关于异常的通用语法:Arrays.< String> asList(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!