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

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.




Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           

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

Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

Leave a Reply

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

Sarmaroof © 2017