Java <T> class declaration

I am familiar with the simple declaration of the class public class test , but I do not understand the public class test<T> .

+4
source share
4 answers

<T> refers to the generic type. Generic types are introduced in Java to provide you compilation time, and this is important due to type erasure, type safety. This is especially useful in collections because it frees you from manual casting.

It is a good idea to read more about generics, especially the documentation on this topic. Angelika Langer is very good: http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

+11
source

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

T is a type parameter or a "general" parameter. Say you have a List. Then for the structure of the list it does not matter what you store there. There can be strings, dates, apples, SpaceShips, it does not matter for operations with lists, such as adding, deleting, etc. That way, you keep it abstract when you define a class ("this is an abstract list"), but specify it when you create 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 clear that every T needs to be a String ... 
+5
source

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

In the Java field, they are called Generics (see also Lesson: General Concepts ).

+1
source

All Articles