Generics Methods and Classes in Java

Generic Methods and Classes allow the developers to specify a single method that can serve the purpose of several methods and similarly specify a single class that can serve the purpose of several types respectively.

Generic Methods:

  1. Generic Method return type should be preceded with a type parameter <T>
  2. The type parameters (T) can be used to declare return types or can act as placeholders for the arguments passed to the method.
  3. The type parameters can represent only reference types (Integer, Byte etc) but not primitive types (int, byte, char etc)

Example:

public class GenericMethodExample {

private GenericMethodExample() {

}

public static GenericMethodExample newInstance() {

return new GenericMethodExample();

}

public <T> void displayArray(T[] genericInput) {

for(T value: genericInput) {

system.out.println(value);

}

}

public static void main(String[] args) {

Integer[] intValues = {1, 2, 3, 4};

String[] stringValues = {generic1, generic2};

GenericMethodExample.newInstance().displayArray(intValues);

GenericMethodExample.newInstance().displayArray(stringValues);

// If its an int[] then it won’t work as generic type parameter has to be a reference type.

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s