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 stringCollection = new HashSet();
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 stringCollection = new HashSet();

for(String stringElement : stringCollection) {
  //do something with each stringElement    
}
You can do the same thing with List'sSet'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.

- Copyright © 2013 Taqi Shah Blogspot -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -