Generic Programming Introduction

Generic Programming Introduction

Good developers always prefer generic programming because a programmer does not need to specify the data type when writing generic programs. As an example, let’s think about a program that sorts data. However, if we are implementing an array of data, a new program or sorting method needs to be written for each data type ( a string array sorter, an integer array sorter, and so on). This is exactly where generic classes and methods come into play. Using this feature of Java, one generic method can be coded, which will effectively apply to all the various data types listed above. This is made possible with generic programming.

As per definition, ‘Java Generic methods and classes allow programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types’. Not only does it generalize code, but it also acts as a safety envelope to catch type mismatch errors and exceptions at compile time.

The methodology that is followed by such generic programs are as follows:

If we take the example of the generic sorting method  for sorting an array of objects, we proceed in the following way:

  • Write a generic method
  • Invoke the method with various arrays of various data types (strings, integer, and so on).

Sample Code

We will be printing an array of various data types using a generic method.

public class GenericDemo
{
public static <E> void printArray (E[] inputArray)
{
for (E element: inputArray)
{
System.out.printf (“%s”, element);
}
System.out.println();
}

public static void main (String args [])
{
Integer[] intArray = { 1, 2, 3};
Double[] doubleArray = {1.1, 2.2, 3.3};

printArray (intArray);
printArray(doubleArray);

}
}

OUTPUT

1 2 3

1.1 2.2 3.3

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.