Java 5: Generics

Java 5 features
 Enhanced for Loop |   Varargs |   Static import |   Autoboxing and unboxing |   Enum types |   Generics |   Annotations |   By date 

The generics is introduced in Java 5 to provide a type-safety at compile time and to avoid the ClassCastException at runtime. By using generics for example you can prevent adding an Integer to a Java collection of Strings.

Generic wildcards.

  1. The Unknown Wildcard List<?> means the list type is unknown. This could be a List<Integer>, a List<StringBuffer> or a List<String> etc.
  2. The extends Wildcard List<? extends MyClass> means a List of instances of the class MyClass or its subclasses.
  3. The super WildcardList<? super MyClass> means a list of either the class MyClass, or a superclass of MyClass.

Example 1: Generics in Java code

What is the output of the following code?

import java.util.ArrayList;

public class MyClass
{
  public static void main(String args[])
  {
    ArrayList<String> movies = new ArrayList<String>();
    movies.add("The Godfather");
    movies.add("The Lord of the Rings");
    movies.add("Amadeus");
    for(String element: movies)
    {
      System.out.println(element);
    }
  }
}
Author: Sar Maroof

Answer explanation

The output of this program is:

The Godfather
The Lord of the Rings
Amadeus





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *