tags:

views:

124

answers:

7

Hi guys, I saw sometimes a type object inside <> beside of another object type declaration. 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 explication? Kind regards

+6  A: 

They're known as generics in java, and templates in C++.

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

sharth
thank you very much!
soneangel
+3  A: 

These are called Generics. Here http://java.sun.com/docs/books/tutorial/java/generics/index.html is a tut from sun for them.

ZeissS
thank you very much!
soneangel
+2  A: 

These are called Generics in Java. They give you a way to tell the compiler what type the collection is going to hold.

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

Mark
+1  A: 

They are Generics, classes that are written with one or more types left to be specified later, so they can be used with any type. The generics can be very useful for containers or algorithms, where the algorithm or the data structure used is independent from the actual type stored or manipulated.

Matteo Italia
+2  A: 

They're called Generics, and allow the compiler to do type checking of contents of lists etc, and also reduces the amount of casting you have to do in your code.

It's also helpful when reading code, as you know what type of object can be put into the item in question, or what type to expect out of it.

Java's implementation isn't as thorough as C++, as Java's is only available at compile time.

At runtime, the type information is no longer available.

Mikezx6r
+1  A: 

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

stacker
+1  A: 

As some others said before: Your dealing with Java Generics. They're in Java since SDK 1.5.

E.g:

new CopyOnWriteArrayList<EventListener>()

means that you're creating a new (concurrent) ArrayList which is able to store objects of type EventListener. If you would create an ArrayList the old (pre Java 1.5) way like:

new ArrayList()

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

pfleidi
Very kind! Very easy explication!
soneangel