Java泛型< T>意义 [英] Java Generics <T> Meaning

查看:62
本文介绍了Java泛型< T>意义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读和审查以下站点,并且有疑问.

I was reading and reviewing the following site and had a question.

https://www.geeksforgeeks.org/angle-在示例中插入括号/

在下面的说明中,它们显示了类定义,后跟< T> ,然后在实际实现这些类时,它们使用不同的类型,例如或作为参数.我的问题是:记号实际上是Java中定义的语法吗?特别是,T是定义泛型"的必要条件吗?那么,这基本上意味着参数可以具有多种不同的类型吗?同样,如果任何人都可以用更简单的术语改写或解释一个泛型的含义,那将非常有帮助.谢谢.

In the explanations below they show class definitions followed by <T> and then when actually implementing these classes they use different types such as or as the parameters. My question is: is the '' notation actually a defined syntax in Java? In particular, is the T a necessary thing in order to define a "Generic"? And then does it basically mean that the parameters can be of multiple different types? Also, if anyone can reword or explain in simpler terms what the meaning of a generic is that would be very helpful. Thanks.

推荐答案

< T> 确实是Java定义的语法,但是您可以使用任何要命名的名称,您不需要使用 T ,例如,这是有效的:

The <T> is indeed a syntax defined by Java, but you can use whatever name you want to name a type, you don't need to use T, for example this is valid:

public class Box<MyType> {
    private MyType t;

    public void set(MyType t) { this.t = t; }
    public MyType get() { return t; }
}

但是,请坚持使用 T 或其他常见的类型名称,因为其他人已经习惯将它们视为通用类型",这样可以简化您的代码读取.

But, stick with T or other common type names, as other people are already used to seeing those as the "generic types" so it makes reading your code simpler.

我建议您阅读有关泛型的Java指南,您可以在其中找到最常用的类型参数名称:

I recommend you read Java's Trail about Generics, where you can find the most commonly used type parameter names:

E - Element
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

至于泛型的含义是什么",请检查此其他页面.

As for "what the meaning of generics is", check this other page.

这篇关于Java泛型&lt; T&gt;意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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