Tech and Media Labs
This site uses cookies to improve the user experience.

Java Collections - Generic Collections

Jakob Jenkov
Last update: 2014-06-23

It is possible to generify the various Collection and Map types and subtypes in the Java collection API. This text will not cover generics in detail. Java Generics is covered in my
Java Generics tutorial.

The Collection interface can be generified like this:

Collection<String> stringCollection = new HashSet<String>();

This stringCollection can now only contain String instances. If you try to add anything else, or cast the elements in the collection to any other type than String, the compiler will complain.

Actually, it is possible to insert other objects than String objects, if you cheat a little (or is just plain stupid), but this is not recommended.

You can iterate the above collection using the new for-loop, like this:

Collection<String> stringCollection = new HashSet<String>();

for(String stringElement : stringCollection) {
  //do something with each stringElement    

You can do the same thing with List's, Set's etc.

I won't get into much more detail about generic collections here. Like I said in the beginning, I have a separate Java Generics tutorial. Additionally, more generic examples will be shown in the texts on the specific collection types.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC