4

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?

1
  • Thank you very much to everyone! I'm ok now ;) and also thanks to edit the title in a right way!! Kind regards Commented Feb 7, 2010 at 20:51

7 Answers 7

8

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

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

Very kind! Very easy explication!
2

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

Comments

2

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

Comments

2

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.

Comments

2

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.