<T>(尖括号)在 Java 中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6607550/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:10:22  来源:igfitidea点击:

What does <T> (angle brackets) mean in Java?

javagenerics

提问by Laughy

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

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

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>意思?这是否意味着我可以创建一个类型的对象T

回答by Joachim Sauer

<>is used to indicate genericsin Java.

<>用于表示Java 中的泛型

Tis a type parameter in this example. And no: instantiating is one of the few things that you can'tdo with T.

T在这个例子中是一个类型参数。不:实例化是您无法使用的少数几件事之一T

Apart from the tutorial linked above Angelika Langers Generics FAQis a great resource on the topic.

除了上面链接的教程之外,Angelika Langers 泛型常见问题解答是有关该主题的重要资源。

回答by Rafiek

is called a generic type. You can instantiate an object Pool like this:

称为泛型类型。你可以像这样实例化一个对象池:

PoolFactory<Integer> pool = new Pool<Integer>();

The generic parameter can only be a reference type. So you can't use primitive types like int or double or char or other primitive types.

泛型参数只能是引用类型。所以你不能使用原始类型,如 int 或 double 或 char 或其他原始类型。

回答by mgiuca

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

<T>泛型,通常可以读作“类型 T”。这取决于 <> 左侧的类型实际上意味着什么。

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

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

Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer>for example, that means "An ArrayListof 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 Stringkeys and Integervalues."

通常,你不会在那里看到“T”,你会看到另一种类型。因此,如果您看到ArrayList<Integer>例如,这意味着“ S 中的一个ArrayListInteger。例如,许多类使用泛型来限制容器中元素的类型。另一个例子是HashMap<String, Integer>,它的意思是“带有String键和Integer值的映射”。

Your Pool example is a bit different, because there you are defininga 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 示例有点不同,因为您正在定义一个类。因此,在这种情况下,您正在创建一个其他人可以使用特定类型代替 T 实例化的类。例如,我可以Pool<String>使用您的类定义创建一个类型的对象。这意味着两件事:

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

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 Integerwherever you see Tin the source.

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

回答by mgiuca

It is related to generics in java. If I mentioned ArrayList<String>that means I can add only String type object to that ArrayList.

它与java中的泛型有关。如果我提到ArrayList<String>这意味着我只能将 String 类型的对象添加到该 ArrayList。

The two major benefits of generics in Java are:

Java 中泛型的两个主要好处是:

  1. Reducing the number of casts in your program, thus reducing the number of potential bugs in your program.
  2. Improving code clarity
  1. 减少程序中的强制转换次数,从而减少程序中潜在错误的数量。
  2. 提高代码清晰度

回答by Adiii

Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects

泛型类是一种在创建时接受数据类型作为参数的类。此类型参数使用尖括号指定,每次实例化该类的新实例时,该类型都可以更改。例如,让我们为 Employee 对象创建一个 ArrayList,为 Company 对象创建另一个

ArrayList<Employee> employees = new ArrayList<Employee>();
ArrayList<Company> companies = new ArrayList<Company>();

You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.

您会注意到我们使用相同的 ArrayList 类来创建两个列表,并且我们使用尖括号传入 Employee 或 Company 类型。拥有一个能够处理多种类型数据的通用类可以减少拥有许多执行类似任务的类。泛型还通过为所有内容提供强类型来帮助减少错误,这有助于编译器指出错误。通过为 ArrayList 指定类型,如果您尝试将 Employee 添加到 Company 列表,编译器将抛出错误,反之亦然。

回答by Ruturaj Mohanty

It's really simple. It's a new feature introduced in J2SE 5. Specifying angular brackets after the class name means you are creating a temporary data type which can hold any type of data.

这真的很简单。这是J2SE 5 中引入的一个新特性。在类名后指定尖括号意味着您正在创建一个可以保存任何类型数据的临时数据类型。

Example:

例子:

class A<T>{
    T obj;
    void add(T obj){
        this.obj=obj;
    }
    T get(){
        return obj;
    }
}
public class generics {
    static<E> void print(E[] elements){
        for(E element:elements){
            System.out.println(element);
        }
    }

    public static void main(String[] args) {
        A<String> obj=new A<String>();
        A<Integer> obj1=new A<Integer>();
        obj.add("hello");
        obj1.add(6);
        System.out.println(obj.get());
        System.out.println(obj1.get());

        Integer[] arr={1,3,5,7};
        print(arr);
    }
}

Instead of <T>, you can actually write anything and it will work the same way. Try writing <ABC>in place of <T>.

取而代之的是<T>,您实际上可以编写任何内容,并且以相同的方式工作。尝试写作<ABC>代替<T>.

This is just for convenience:

这只是为了方便:

  • <T>is referred to as any type
  • <E>as element type
  • <N>as number type
  • <V>as value
  • <K>as key
  • <T>被称为任何类型
  • <E>作为元素类型
  • <N>作为数字类型
  • <V>作为价值
  • <K>作为关键

But you can name it anything you want, it doesn't really matter.

但是你可以给它任何你想要的名字,这并不重要。

Moreover, Integer, String, Booleanetc are wrapper classes of Java which help in checking of types during compilation. For example, in the above code, objis of type String, so you can't add any other type to it (try obj.add(1), it will cast an error). Similarly, obj1is of the Integertype, you can't add any other type to it (try obj1.add("hello"), error will be there).

此外,IntegerStringBoolean等都是包装类的Java,帮助在编译过程中的类型检查。例如,在上面的代码中,obj是 type String,所以你不能向它添加任何其他类型(尝试obj.add(1),它会抛出错误)。同样,obj1is 的Integer类型,您不能向其添加任何其他类型(尝试obj1.add("hello"),错误将在那里)。