Reading:  

Quick walk through the advanced concepts in Java - Part 3 of series


Working with Generics

Generics are supported from JDK 5. Generics define algorithm once and apply it on any kind of datatype without additional effort.

At high level generics are known as parameterized types. Generics help to create single class which will be useful to implement on multiple data types. A interface,class or a method that operates on a parameterized type is known generics interface ,class or method.

Generics are compile-time type safety which allows programmers to catch invalid types during compile time.

Generic Methods:

Based on types of arguments passed to generic method compiler handles each method calls appropriately. Following are rules that define Generic Methods:

  • All generic method declarations will have type parameter section delimited by angle brackets (< and >) that precedes method's return type.
  • Each type parameter section contains one or more type parameters separated by commas.
  • The type parameters will be used to declare return type and act as placeholders for types of arguments passed to generic method which are called as actual type arguments.
  • A generic method's body is declared like that of any other method.

Example

public class GenericExampleMethodTest {
	//  printArray generic method                         
	public static < T > void printArray(T[] inputArray) {
		// array elements   Display            
		for (T element: inputArray) {
			System.out.printf("%s ", element);
		}
		System.out.println();
	}

	public static void main(String args[]) {
		// Create arrays of Integer, Double and Character
		Integer[] intArray = {
			2, 8, 9, 7, 10
		};
		Double[] doubleArray = {
			5.1, 5.2, 6.3, 7.4
		};
		Character[] charArray = {
			'J', 'A', 'V', 'A'
		};

		System.out.println("IntegerArray :");
		printArray(intArray); // Integer array

		System.out.println("\n DoubleArray :");
		printArray(doubleArray); // Double array

		System.out.println("\nCharacterArray :");
		printArray(charArray); // Character array
	}
}
 

OutPut:

IntegerArray: 2 8 9 7 10
DoubleArray: 5.1 5.2 6.3 7.4
CharacterArray: J A V A

Bounded Type Parameters:

Sometimes when we want to restrict types that can be used as type arguments in a parameterized type for example a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

To declare a bounded type parameter, list type parameter's name, followed by extends keyword, followed by its upper bound.

public class MaximumElement {
	public static < T extends Comparable < T >> T MaximumElement(T x, T y, T z) {
		T max = x; // assume x is initially the largest       
		if (y.compareTo(max) > 0) {
			max = y; // y is the largest so far
		}
		if (z.compareTo(max) > 0) {
			max = z; // z is the largest now                 
		}
		return max; // returns the largest object   
	}
	public static void main(String args[]) {
		System.out.printf("Max of %d, %d and %d is %d\n\n",
		7, 8, 9, MaximumElement(7, 8, 9));

		System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
		2.4, 4.4, 6.4, MaximumElement(2.4, 4.4, 6.4));

		System.out.printf("Max of %s, %s and %s is %s\n", "s",
			"b", "c", MaximumElement("s", "b", "c"));
	}
}


OutPut:

Max of 7,
8 and 9 is 9
Max of 2.4,
4.4 and 6.4 is 6.4
Max of s,
b and c is s

Generic Classes:

A generic class declaration looks like a non-generic class declaration except that class name is followed by a type parameter section.

A generic methods type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

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 > Boxinteger = new Box < Integer > ();
		Box < String > Boxstring = new Box < String > ();
		Boxinteger.add(new Integer(20));
		Boxstring.add(new String("Java"));
		System.out.printf("Value Integer:%d\n\n", Boxinteger.get());
		System.out.printf("Value String :%s\n", Boxstring.get());
	}
}


Output:

Value Integer: 20
Value String: Java

 

 

Description

This is the last part in our tutorial series on Java. This tutorial is designed as a quick walk through the advanced concepts of Java Languages. This tutorial is subdivided into few chapters as shown below

  1. Data Structures
  2. Collections
  3. Generics
  4. Serialization
  5. Networking 
  6. Working with Emails
  7. Multithreading
  8. Getting started with Applets
  9. JavaDoc

Let us know if you find any issues with this tutorial. Also, if you can provide us with your feedback, that always help us improve.

 



Prerequisites

You must have read Part 1 and Part 2 of our tutorial series on Java.

Audience

Beginners or students looking to brush up their Java knowledge

Learning Objectives

To get an understanding on some of the advanced topics of Java.

Author: Subject Coach
Added on: 10th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!