什么是 <T>(尖括号)在Java中是什么意思? [英] What does <T> (angle brackets) mean in Java?

查看:34
本文介绍了什么是 <T>(尖括号)在Java中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Java,最近被尖括号 (<>) 难住了.它们究竟是什么意思?

I am currently studying Java and have recently been stumped by angle brackets(<>). What exactly do they mean?

public class Pool<T>{
    public interface PoolFactory<T>{
        public T createObject();
    }
    this.freeObjects = new ArrayList<T>(maxsize)
}

是什么意思?这是否意味着我可以创建 T 类型的对象?

What does the <T> mean? Does it means that I can create an object of type T?

推荐答案

是一个泛型,通常可以读作类型 T".这取决于 <> 左侧的类型实际上意味着什么.

<T> is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.

我不知道 PoolPoolFactory 是什么,但你也提到了 ArrayList,这是一个标准的 Java类,所以我会谈谈.

I don't know what a Pool or PoolFactory is, but you also mention ArrayList<T>, which is a standard Java class, so I'll talk to that.

通常,您不会在其中看到T",您会看到另一种类型.因此,例如,如果您看到 ArrayList,则表示ArrayList of Integers".例如,许多类使用泛型来限制容器中元素的类型.另一个例子是 HashMap,意思是一个带有 String 键和 Integer 值的映射."

Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer> for example, that means "An ArrayList of Integers." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>, which means "a map with String keys and Integer values."

您的 Pool 示例有点不同,因为您正在定义一个类.因此,在这种情况下,您正在创建一个其他人可以使用特定类型代替 T 实例化的类.例如,我可以使用您的类定义创建一个 Pool 类型的对象.这意味着两件事:

Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String> using your class definition. That would mean two things:

  • 我的Pool 将有一个接口PoolFactory 和一个createObject 方法返回Strings.
  • 在内部,Pool 将包含一个 ArrayList 字符串.
  • My Pool<String> would have an interface PoolFactory<String> with a createObject method that returns Strings.
  • Internally, the Pool<String> would contain an ArrayList of Strings.

这是个好消息,因为在另一个时间,我可以创建一个 Pool,它会使用相同的代码,但在任何地方都有 Integer参见源码中的 T.

This is great news, because at another time, I could come along and create a Pool<Integer> which would use the same code, but have Integer wherever you see T in the source.

这篇关于什么是 &lt;T&gt;(尖括号)在Java中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆