Java Generics?

generics, java

Solution

From http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

Here is a simple example taken from the existing Collections tutorial:

    // Removes 4-letter words from c. Elements must be strings
    static void expurgate(Collection c) {
        for (Iterator i = c.iterator(); i.hasNext(); )
          if (((String) i.next()).length() == 4)
            i.remove();

}

Here is the same example modified to use generics:

    // Removes the 4-letter words from c
    static void expurgate(Collection<String> c) {
        for (Iterator<String> i = c.iterator(); i.hasNext(); )
          if (i.next().length() == 4)
            i.remove();

}

Sorry for the direct c&p but I found that this write up was better than something I could have written.

Edit to include a good point made in the comments:

Generics are not limited to communicating the type of a collection to the compiler...the collections library just happened to be a good way to demonstrate them.

Problem

Over the years I seen many people use the word "generics", I honestly have not a clue what it means, whatever it is I most likely use it but just don't know that it was called that. :p

Original source

Related problems