Java泛型方法声明基础 [英] Java generic method declaration fundamentals
问题描述
我开始为 Java
学习 Generics
,我读了几个教程,但我有点困惑并且不确定如何声明泛型方法。
I'm starting to learn Generics
for Java
and I read several tutorials, but I'm a bit confused and not sure how a generic method is declared.
当我使用泛型类型时,定义方法的正确顺序是什么?我找到了这个样本,什么时候需要使用尖括号?什么时候不需要?
When I use a generic type, what is the correct order to define the method? I found this sample, when do I need to use the angle brackets and when not?
public class Box<A> {
private A a;
...
public void setA(A a) {
this.a = a;
}
public <A> List<A> transform(List<A> in) {
return null;
}
public static <A> A getFirstElement(List<A> list) {
return null;
}
public A getA() {
return a;
}
推荐答案
问题是你的代码使用相同的字符A,但它在不同的地方有几个不同的含义:
The problem is that your code is using the same character A, but it has several different "meanings" in the different places:
public class Box<T> {
需要大括号,因为您在这里说:Box使用通用类型,称为T.
braces required, because you are saying here: Box uses a generic type, called T.
用法 T没有大括号:
private T a;
public void setA(T a) {
但是
public <T2> List<T2> transform(List<T2> in) {
正在引入另一个类型参数。我把它命名为T2,以明确它转换
。其他方法不知道T2!
is introducing another type parameter. I named it T2 to make it clear that it is not the same as T. The idea is that the scope of T2 is only that one method transform
. Other methods do not know about T2!
public static <A> A getFirstElement(List<A> list) {
与上面相同 - 此处为T3; - )
Same as above - would be "T3" here ;-)
编辑您的评论:您不能使用静态方法使用类范围类型T.这根本不可能!有关原因,请参见此处!
EDIT to your comment: you can't have a static method use the class-wide type T. That is simply not possible! See here for why that is!
编辑2:通用版允许您编写泛型的代码(因为它可以处理不同的类);但仍然给你编译时安全性。示例:
EDIT no.2: the generic allows you to write code that is generic (as it can deal with different classes); but still given you compile-time safety. Example:
Box<String> stringBox = new Box<>();
Box<Integer> integerBox = new Box<>();
integerBox.add("string"); // gives a COMPILER error!
在人们使用仿制药之前,他们只能处理全部的对象地点;和手工铸造。
Before people had generics, they could only deal with Object all over the place; and manual casting.
这篇关于Java泛型方法声明基础的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!