java java类声明<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3633768/
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
java class declaration <T>
提问by Brain
I'm familiar with simple class declaration public class test
but I don't understand public class test<T>
.
我熟悉简单的类声明,public class test
但我不明白public class test<T>
.
回答by nkr1pt
< T > refers to a generic type. Generic types are introduced in Java to provide you with compile time, and this is important due to type erasure, type-safety. It's especially useful in Collections because it frees you from manual casting.
<T> 指的是泛型类型。Java 中引入了泛型类型来为您提供编译时间,由于类型擦除和类型安全,这很重要。它在 Collections 中特别有用,因为它使您免于手动转换。
It is a good idea to read more on generics, especially the documentation on the topic by Angelika Langer is very good: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
阅读更多关于泛型的内容是个好主意,尤其是 Angelika Langer 关于该主题的文档非常好:http: //www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
回答by Landei
I assume that HTML ate your <T> (you need to write <T> to display it)
我假设 HTML 吃了你的 <T> (你需要写 <T> 来显示它)
T is a type parameter or "generic" parameter. Say you have a List. Then it is for the structure of the list unimportant what exactly you are storing there. Could be Strings, Dates, Apples, SpaceShips, it doesn't matter for list operations like add, remove etc. So you keep it abstract when defining the class ("this is an abstract list"), but specify it when you instantiate it ("this is a list of Strings")
T 是类型参数或“通用”参数。假设你有一个列表。那么对于列表的结构来说,你究竟在那里存储了什么并不重要。可以是字符串、日期、苹果、SpaceShips,对于添加、删除等列表操作无关紧要。因此在定义类时保持抽象(“这是一个抽象列表”),但在实例化时指定它(“这是一个字符串列表”)
//in Java, C# etc would be similar
//definition
public class List<T> {
public void add(T t) { ... }
public void remove(T t) { ... }
public T get(int index) { ... }
}
//usage
List<String> list = new List<String>();
list.add("x"); //now it's clear that every T needs to be a String
...
回答by László van den Hoek
You are probably referring to Java Generics:
您可能指的是 Java 泛型:
http://www.oracle.com/technetwork/java/javase/generics-tutorial-159168.pdf
http://www.oracle.com/technetwork/java/javase/generics-tutorial-159168.pdf
回答by missingfaktor
This is parametric polymorphism, another important form of polymorphism other than subtyping.
这是参数多态性,是除子类型之外的另一种重要的多态性形式。
In Java land, they call it Generics(see also Lesson: Generics).