In Java, what does this mean when the type is followed by angle brackets (as in List <Foo>)?

I sometimes saw a type object inside <> next to the declaration of another type of object. For instance:

NavigableMap<Double, Integer> colorMap = new TreeMap<Double, Integer>() or private final CopyOnWriteArrayList<EventListener> ListenerRecords = new CopyOnWriteArrayList<EventListener>(); 

Could you give me an easy explanation?

+5
source share
7 answers

They are known as generics in java and templates in C ++.

http://java.sun.com/developer/technicalArticles/J2SE/generics/

+9
source

They are called generics. Here http://java.sun.com/docs/books/tutorial/java/generics/index.html is from the sun for them.

+3
source

As some others have said: you are dealing with Java Generics. They are in Java with the SDK 1.5.

eg:

 new CopyOnWriteArrayList<EventListener>() 

means that you are creating a new (parallel) ArrayList that can store objects of type EventListener. If you create an ArrayList in the old way (pre Java 1.5), for example:

 new ArrayList() 

All contained objects will be of type Object, and you will have to attribute them to their real type. See also http://en.wikipedia.org/wiki/Generics_in_Java#Motivation_for_generics .

+3
source

They are called Generics in Java. They give you a way to tell the compiler which type of collection will be held.

http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html

+2
source

They are called Generics and allow the compiler to check the types of contents of lists, etc., and also reduce the number of castings that you must do in your code.

This is also useful when reading code, since you know what type of object can be placed in the element in question or what type to expect from it.

The Java implementation is not as thorough as C ++, since Java is only available at compile time.

At run time, type information is no longer available.

+2
source

In your TreeMap example, the TreeMap key is of type Double, and the value referenced by this key is of type Integer. And as already answered, he called generics. This is an extension introduced in java 1.5. This makes the code more readable.

+2
source

These are Generics , classes that are written in one or more types will be specified later, so they can be used with any type. Generics can be very useful for containers or algorithms where the algorithm used or the data structure does not depend on the actual type that is stored or managed.

+1
source

Source: https://habr.com/ru/post/904648/


All Articles