Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does <E> mean in Collection<E>?

What meaning has <E> on the code Collection<E>?

like image 255
Johanna Avatar asked Jun 29 '09 06:06

Johanna


People also ask

What is E collection E?

It means that you're dealing with a collection of items with type E .

What is the E in ArrayList E?

ArrayList <E> list = new ArrayList <> (); The important thing here out is that E here represents an object datatype imagine be it Integer here. The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

What is E in Java docs?

Type Parameter Naming Conventions The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key.

What are collection classes?

Collections class is one of the utility classes in Java Collections Framework. The java. util package contains the Collections class. Collections class is basically used with the static methods that operate on the collections or return the collection.


1 Answers

It means that you're dealing with a collection of items with type E. Imagine you've got a cup of tea. Instead of tea, it could also hold coffee so it makes sense to describe the cup as a generic entity:

class Cup<T> { … }

now you could fill it, either with coffee or tea (or something else):

Cup<Tea> cuppa = new Cup<Tea>();
Cup<Coffee> foamee = new Cup<Coffee>();

In order for this to work, both Tea and Coffee would need to be types defined in your program as well.

This is a compile-time constraint on your code. Coming back from the (rather useless) cup example, collections (arrays, lists …) usually contain items of one type, e.g. integers or strings. Generics help you to express this in Java:

Collection<String> strList = new ArrayList<String>();
strList.add("Foobar"); // Works.
strList.add(42);       // Compile error!

Notice the compile error above? You only get this when using generics. The following code also works, but would not give the nice error message:

Collection strList = new ArrayList();
strList.add("Foobar"); // Works.
strList.add(42);       // Works now. Do we really want this?!
like image 93
Konrad Rudolph Avatar answered Sep 21 '22 19:09

Konrad Rudolph