Java Generics - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts


Generics enable classes and interfaces to be parameters when an interface, class or method is defined. If you use generics, strong type checking is performed by the Java compiler

The code snippet without generics
List mylist = new ArrayList(); mylist.add("hello"); String str = (String) mylist.get(0);
Code snippet with generics:
List<String> mylist = new ArrayList<String>(); mylist.add("hello"); String str = mylist.get(0);

Generic Class


In a generic class declaration a type parameter section is added with non-generic class declaration.

The type parameters of generic methods need to be set as type parameters of the class containing the methods. If multiple parameters are used, they should be separated by commas. Thus generic classes are known as parameterized classes or parameterized types.

A generic class is defined below
package com.t4b.test; public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> ib = new Box<Integer>(); Box<String> sb = new Box<String>(); ib.add(new Integer(10)); sb.add(new String("How are you")); System.out.printf("Integer value :%d\n\n", ib.get()); System.out.printf("String value :%s\n", sb.get()); } }

Generic Method


A generic method can be called with different types of arguments. The compiler handles appropriate method call for different types arguments to the generic methods.

A generic method's body is declared alike a non-generic method
public class GenericMethodTest { public static <E> void print( E[] arr ) { for ( E el : arr ){ System.out.printf( "%s ", el ); } System.out.println(); } public static void main( String args[] ) { Integer[] intArr = { 1, 2, 3, 4, 5 }; Double[] doubleArr = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArr = { 'H', 'E', 'L', 'L', 'O' }; print( intArray ); print( doubleArray ); print( charArray ); } }


Happy Exploring!

No comments:

Post a Comment