Showing posts with label Generics. Show all posts
Showing posts with label Generics. Show all posts

What are Generics in Java with example. How to improve type safety of your code?

In core java interview , question like "what are generics? and the advantages of using generics?" may be asked. This tutorial answers the above questions with example code.
Introduction of generics in the Java programming improves the type safety of your code also helps to reduce the runtime errors because it makes more of your bugs detectable at compile time. This powerful feature of Java introduced in the release of JDK 5 which allows a type or method to operate on objects of various types . To implement generics , special syntax is used . Generics also enhance the Java language with special syntax to iterate entities of Lists, Map,etc. Following code illustrates how coding mistake can happen without using generics and how to avoid it ? ArrayList can contain multiple data types like String , Integer and others. Before JDK 5, there was nothing in Java to restrict this behavior, which caused many coding mistakes.

import java.util.ArrayList;
public class generics
{
public static void main(String arg[])
{
List al= new ArrayList();
al.add("one");
al.add(2);  // no compile error occurs
al.add("three");
accessList(al);
}
private static void accessList(List al) {
   for (int k = 0; k < al.size(); k++) {
     String s =(String) al.get(k);  //  runtime error  "java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String "occurs when the integer value is accessed 
   System.out.println(s);
   }
} 

To ensure the assignment to a variable of type String is type safe, the type casting is required. Now the above code can be written using generics to avoid the runtime errors.

List<String> genericsAL = new ArrayList<String>();
genericsAL.add("one");
//genericsAL.add(2); // this line makes compile error 
genericsAL.add("three");
accessGenericsList(genericsAL);
}
private static void accessGenericsList(List<String> al) {
   for (int k = 0; k < al.size(); k++) {
     String s =al.get(k);      //  No type casting is required. 
   System.out.println(s);
   }
} 

List<String> genericsAL = new ArrayList<String>(); Generic used in the statement enforces to accept only Strings. The following statement gives compile time error.
List<Object> genericsO = genericsAL;
List<String> genericsAL = new ArrayList<String>() - List is a generic interface that takes a type parameter (in this case String) . The type declaration for the variable genericsAL specifies that this is a List of Strings, written List<String> and no type casting is required for the line String s =al.get(k)
iterate using generics
If you want to iterate the above List using generics , you can use the following statement. For iterating the list using generics , a special syntax is used
for (String s : al ) System.out.println(s);
Let us see the how to define a Simple Generics . The interfaces List, Collection and Iterator are defined in package java.util for using generics as follows

public interface List<E> extends Collection<E>{
    void add(E x);
    Iterator<E> iterator();
}
public interface Iterator<E>{
    E next();
    boolean hasNext();
}

The element within the angle brackets are the declarations of the formal type parameters of the interfaces List , Collection and Iterator .All occurrences of the formal type parameter are replaced by the actual type argument. In our example , E is replaced with String.
The following code snippet accepts any kind of collection as a parameter and prints the elements.

   void displayCollection(Collection c) {
    Iterator i = c.iterator();
    for (k = 0; k < c.size(); k++) {
        System.out.println(i.next());
    }
}

How to write the equivalent code for the above code using generics. We can't use Collection<Object> . Because it accepts only Object type. Use wildcard type to accept any kind of collection. i.e Collection<?> -(called as collection of unknown ) collection whose element type matches anything . The code snippet is as follows

 void displayCollection(Collection<?> c) {
    for (Object e : c) {
        System.out.println(e);
    }
}

For example of HashMap using generics , you can visit my earlier post , Traverse HashMap
Note : Just like type declarations, method declarations can be generic . This is called generic methods. We can see generic methods with example in the later post.

Read more...

 
Copyright 2011 Java Online