Java Generics tutorial.
The Collection interface can be generified like this:
Collection
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:
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.
No comments:
Post a Comment