java class declaration <T>

北城以北 提交于 2019-11-30 18:02:24

问题


I'm familiar with simple class declaration public class test but I don't understand public class test<T>.


回答1:


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

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




回答2:


I assume that HTML ate your <T> (you need to write &lt;T&gt; to display it)

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

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



回答3:


You are probably referring to Java Generics:

http://www.oracle.com/technetwork/java/javase/generics-tutorial-159168.pdf




回答4:


This is parametric polymorphism, another important form of polymorphism other than subtyping.

In Java land, they call it Generics (see also Lesson: Generics).



来源:https://stackoverflow.com/questions/3633768/java-class-declaration-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!