Generics

Objects may be restricted to using a single type with type parameters.

Type parameters are declared using the angle brackets, immediately following the object declaration.

Generics help code a single class that can be used for several types, instead of defining different classes for different types.

Benefits
– Good for maintenance
– less prone to errors
– compile time type safety
– works for subtypes too

Caution
Never use the Object class as a type parameter. It doesn’t work for Object super type.

A complete example

Here’s an example of a class that is modelled after the array data structure in Java.

import java.util.*;

public class Array<T> implements Iterable
{
	int size;
	int count = 0;
	Object[] o;
	int next = 0;
	private Array() {}
	
	public Array(int size) {
		this.size = size;
		o = new Object[size];
	}

	public void add(T t) {
		if(count < size) {
			o[count++] = t;
		}
	}
	
	public T get(int index) {
		if(index < size && index >= 0) {
			return (T)o[index];
		}
		return null;
	}
	
	public int size() {
		return size;
	}
	
	public Iterator iterator() {
		// reset
		next = 0;
		return new ArrayIterator();
	}
	
	class ArrayIterator implements Iterator
	{
		@Override
		public boolean hasNext()
		{
			return (next < size);
		}

		@Override
		public Object next()
		{
			return get(next++);
		}

		@Override
		public void remove()
		{
			// TODO: Implement this method
		}
	}
	
	public static void main(String[] args) {
		Array<Integer> array =new Array<Integer>(5);
		array.add(5);
		array.add(17);
		array.add(54);
		array.add(37);
		array.add(33);
		array.add(66);
		
		Array.ArrayIterator it = array.new ArrayIterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		System.out.println("---------");
		
		Array<String> strings = new Array<String>(3);
		strings.add("Sarita");
		strings.add("Akash");
		strings.add("Romeo");
		
		Iterator iterator = strings.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		
		System.out.println("---------");
		
		for(int i=0; i<strings.size(); i++) {
			System.out.println(strings.get(i));
		}
		
		System.out.println("---------");
		
		it = strings.new ArrayIterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
	}
	
}

Advertisements

Author: Anand Betanabhotla

Corporate Trainer

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