Originally posted by Allion Salvador:
Isn't the point to be able to put different kinds of objects in it?
It's actually quite rare in real programs to have a specific collection of objects that don't share a common type. If they're not all of the same class, then they'll virtually always share a common interface or superclass -- i.e., if they're not all Cows, then they're probably all Mammals.
So it's nice that ArrayLists can store any kind of object -- but a single individual ArrayList is essentially never called on to store more than one kind of object. I don't know that I've ever programmed an ArrayList that contained (for example) a Cow, a
String, and an int[].
Anyway, by declaring that you've got an ArrayList<Cow>, you avoid having use ugly (and potentially incorrect) type casts -- i.e., instead of
((Cow) theList.get(0)).moo();
you can simply write
theList.get(0).moo();
and the nice thing is that if you've gotten confused and tried to make a Dog moo(), the first version will throw an exception at runtime, but the second version will fail to compile. That means you fix the problem right after you make the mistake, instead of a week later when a user reports the problem to you.
Make sense?