java Java泛型方法声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14979342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java generic method declaration
提问by ZeDonDino
I'm learning Java generics and I ask myself this question.
我正在学习 Java 泛型,我问自己这个问题。
What is the difference between these two method declarations?
这两个方法声明有什么区别?
public static void someMethod(List<? extends Number> numberList);
and
和
public static <E extends Number> void someMethod(List<E> numberList);
采纳答案by Rich O'Kelly
In the latter you have a reference to the type within the scope of someMethod
, namely E
. In the former you do not.
在后者中,您可以引用 范围内的类型someMethod
,即E
. 在前者你没有。
回答by Adam Arold
The main difference is that the latter is a generic methodthe former is not.
主要区别在于后者是一种通用方法,前者不是。
So for example in the latter method you can do something like this:
因此,例如在后一种方法中,您可以执行以下操作:
public static <E extends MyObject> void someMethod(List<E> someList) {
E myObject = someList.iterator().next(); // this can actually lead to errors
myObject.doSomething(); // so treat it as an example
}
This means that you can substitute an arbitrary type E
which conforms to the rule in the generic method declaration and be able to use that type in your method.
这意味着您可以替换E
符合泛型方法声明中规则的任意类型,并且能够在您的方法中使用该类型。
Be advised though that you should call the generic method with type arguments like this:
但请注意,您应该使用这样的类型参数调用泛型方法:
someClass.<MyArbitraryType>someMethod(someList);
You can find a nice overview of generic methods here.
您可以在此处找到对泛型方法的很好的概述。
回答by Landei
With the second version you can do something like:
使用第二个版本,您可以执行以下操作:
public static <E extends Number> void someMethod(List<E> numberList) {
E number = numberList.get(0);
numberList.add(number);
}
This isn't possible with the first version.
这在第一个版本中是不可能的。
回答by Denis Rosca
Using the first method declaration will not allow you to add anything new to the list. For example this will not compile.
使用第一个方法声明将不允许您向列表添加任何新内容。例如,这将无法编译。
public static void someMethod(List<? extends Number> numberList, Number number) {
numberList.add(number);
}
while the second allows you to do this:
而第二个允许你这样做:
public static <T extends Number> void someMethod(List<T> numberList, T number) {
numberList.add(number);
}