[英]What does “T” represent in this code?
T get(int i) {
if (i < 0 || i > n - 1) throw new IndexOutOfBoundsException();
return a[i];
}
T set(int i, T x) {
if (i < 0 || i > n - 1) throw new IndexOutOfBoundsException();
T y = a[i];
a[i] = x;
return y;
}
I'm looking over some coding examples from my textbook, but they never mention what T is. 我正在看课本中的一些编码示例,但它们从未提及T是什么。 I'm not sure how to search about this since I don't know what it's called or it's purpose. 我不知道该如何搜索,因为我不知道它的名字或目的。 I was wondering if someone can show me a write-up or some info about this. 我想知道是否有人可以给我看一下这篇文章或一些信息。 Thank you 谢谢
T
represents an object type using generics . T
代表使用泛型的对象类型。
Whatever type x
is in the set
call, the set
method will return that same type. 无论set
调用中的x
是什么类型, set
方法都将返回相同的类型。 In the get
call, the return type is T
, too. 在get
调用中,返回类型也是T
That type must be defined somewhere else, probably in the type of the class, where it might show up as <T>
. 该类型必须在其他地方(可能在类的类型中)定义,在其他地方可能显示为<T>
。
So if this is a class that is some sort of collections (since it is dealing with indexes), it might be defined as: 因此,如果这是一个具有某种集合的类(因为它正在处理索引),则可以将其定义为:
public class SomeCollection<T> {
Then it might get instantiated like: 然后,它可能被实例化为:
SomeCollection<String> arr = new SomeCollection<String>();
In that case, T
would be String
, and the return type of the get
and set
methods, and the type of set
parameter x
, would all be String
. 在这种情况下, T
将为String
,并且get
和set
方法的返回类型以及set
参数x
的类型均为String
。
If it gets instantiated like: 如果它被实例化为:
SomeCollection<Integer> arr = new SomeCollection<Integer>();
then T
is an Integer
. 那么T
是一个Integer
。
You could have both in the same code, without having to write two (or more) different versions of SomeCollection
. 您可以在相同的代码中同时拥有这两个代码,而无需编写两个(或更多)不同版本的SomeCollection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.