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

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

问题描述

我目前正在学习Java,并且最近被尖括号(<>)难倒了。它们究竟意味着什么?

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

< T> 是什么意思?这是否意味着我可以创建一个类型为 T

解决方案

< T> 是一个通用,通常可以读作T型。它取决于<>左侧的类型。



我不知道什么是 Pool PoolFactory 是,但是您也提到了 ArrayList< T> ,它是一个标准的Java类,所以我会和你谈谈。



通常,你不会在那里看到T,你会看到另一种类型。因此,例如,如果您看到 ArrayList< Integer> ,那意味着整数的An ArrayList 秒。例如,许多类使用泛型来约束容器中元素的类型。另一个例子是 HashMap< String,Integer> ,这意味着带有字符串键和整数值。



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


  • 我的 Pool< String> PoolFactory< String> 带有 createObject 方法返回 String s

  • 在内部, Pool< String> 将包含 ArrayList


这是一个好消息,因为在另一段时间,我可以创建一个 Pool< ;整数> ,它会使用相同的代码,但无论您看到 T ,都有 Integer 在源文件中。

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)
}

What does the <T> mean? Does it means that I can create an object of type 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.

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.

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."

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:

  • 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.

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天全站免登陆