You probably don't need it, but I'll preface my response with a simple inheritance review.
Basic class inheritance review
Lets say we have the following classes:
Code:
class Animal {
//code
}
class Cat extends Animal {
//code
}
Some examples:
Code:
// This is valid because Cat is a sub type of Animal
Animal a = new Cat();
// This is not valid
Cat c = new Animal();
In Java, all classes are sub types of the class Object. Some examples:
Code:
Object myObject = new Cat();
//Now we can't generally assign the type Object to a Cat
//Cat myCat = myObject; //this is invalid
//but if know the Object is a Cat (as we do with 'myObject'),
//then we can cast it to a Cat
Cat myCat = (Cat) myObject;
If you cast wrong, you'll get an error when your program executes the cast (it will not error during compilation).
Example:
Code:
Integer myInteger = new Integer(1);
Cat myCat = (Cat) myInteger; //this compiles, but will throw an exception (an error) when it actually executes
My response to your question
I'm going to show you excerpts from the actual Java library source code.
The class LinkedList looks like this:
Code:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
//a bunch of code
}
The important part is "LinkedList<E>". When you declare your class of LinkedList, you can specify what E is.
For example:
Code:
//A list containing integers
LinkedList<Integer> myIntList = new LinkedList<Integer>();
Whatever you choose for this E, will be used throughout the file.
For example, the get() method in LinkedList is as follows:
Code:
public E get(int index) {
return entry(index).element;
}
Since we specified E to be Integer, get will return an Integer.
If you don't specify E, then E defaults to Object.
Code:
LinkedList myList = new LinkedList();
So to compare the two:
Code:
//Without generics
LinkedList myList = new LinkedList();
myList.add(123);
Object o = myList.get(0); //returns type Object
// Even though it returns an Object, we know it is really an Integer,
// so we can cast it from Object to Integer
Integer i = (Integer) myList.get(0);
Code:
//With generics
LinkedList<Integer> myList = new LinkedList<Integer>();
myList.add(123);
Integer i = myList.get(0); //returns type Integer
Short answer
If you don't use generics, your collection will contain Object types. You can put any type into the collection (since all types are subtypes of Object). However, when you retrieve items out of the collections, they will be of type Object, so you'll have to cast them back to their actual type.
If you use generics, you can specify the exact type that the collection will contain.
You should probably always use generics. I can't really think of a good example where you would not want to.
The reason you see code examples without generics is that generics did not always exist.