Java Generics

I am going to keep and track some of the knowledge I pick up on Java and Groovy in the blog for SWMBO and me. Here's the first of them.

Java is a statically typed OO language, laying a lot of emphasis on the particular type of an Object. Is it is a bird, a plane or Superman? But in the inheritance model of Java everything subclasses an Object. In effect where a bird should be, you could coerce an Object to be. Like so:
Bird bird = (Bird) object;
Now if the object happens to be a particular static type at compile time, which is not Bird, the compiler will throw an error. BUT if we resolve the value of object from a method which returns an Object (say a Java 1.4 collection method), we can typecast it into anything including a bird. Whats worse here is that typecasts should typically be along an inheritance tree, but what we get it is people attempting to make a bird out of a plane and so on.

Defeats the overall purpose of a statically typed language doesn't it? That's why ages ago in Java 5, Generics were introduced. The idea was to allow Collections (which had the most problems with unsafe types) to confidently identify the type of the contained elements. It does restrict your Collection to a particular type of course, but how usually do you want a List to contain Integers and Strings?

Generics introduced its own syntax, notations, wildcards and vm changes, most of which no one understands. I will try to compile (*snicker*) some of my thoughts here, more to learn generics correctly than to disseminate any information. Why am I bothering to gather info freely available with a google search? Simple, a lot of info out there is wrong. Like I said not a lot of people completely understand OR correctly use generics.

Consider it my first internet brain-drain exercise.