Generics

  • is a method of allowing abstraction over types
  • makes classes more dynamic in handling types
  • generic object/class accepts different types as its parameters

Purpose

  • Abstraction over Type
    • a class will not be bounded by a specific type
  • Enforce Compile Time Type Safety
    • moves checking of ClassCastException to compilation time
  • Strengthens Relationships
  • Declaration of Programmers Intent
    • code states how class must be used instead of focusing on type
  • Removes the need of casting

Syntax

public class Sample<T>{
	// class code
}

The capital T is a variable known as type parameter , capable of accepting any type.

  • T -Type
  • E - Element
  • K - Key
  • N - Number
  • V - Value

Limitation

Limited to the following:

  • Instantiate a generic type
  • Use primitive generic type
  • Infer compatibility with classes

Application

public class List<T>{
    private Object[] data;
    private int ptr;
    public List(){
        this(10);
    }
    public List(int count){
        data = new Object[count];  
        ptr = 0;
    }
    public T get(int index){
        if(index>=0 && index<ptr){
            return (T) data[index];
        }
        return null;
    }
    public void set(int index, T item){
        if(index>=0 && index<ptr){
            data[index] = item;
        }
    }
    public void add(T item){
        if(ptr>=data.length){
            Object[] temp = new Object[data.length*2];
            for(int i=0; i<data.length; i++){
                temp[i] = data[i];
            }
            data = temp;
        }
        data[ptr] = item;
        ptr++;
    }
    public T remove(int index){
        if(index>=0 && index<ptr){
            T item = (T) data[index];
            for(int i=index+1; i<ptr; i++){
                data[i-1] = data[i];
            }
            ptr--;
            data[ptr] = null;
            return item;
        }
        return null;
    }
    public int size(){ return ptr; }
    public String toString(){
        String result = "List: [";
        if(ptr>0){
            result += data[0];
            for(int i=1; i<ptr; i++){
                result += ", " + data[i];
            }
        }
        result += "]";
        return result;
    }

Runner Program

import java.util.Scanner;
public class Main{
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        List<String> myList = new List<String>();
        int choice = 0;
        do{
            System.out.println("String List Program using Generics");
            System.out.println("1. Add a string");
            System.out.println("2. Remove a string");
            System.out.println("3. Modify a string");
            System.out.println("4. View string list");
            System.out.println("5. Exit");
            System.out.print("Enter choice: ");
            choice = sc.nextInt();
            switch(choice){
                case 1:
                    System.out.print("Enter a string: ");
                    myList.add(sc.next());
                    break;
                case 2:
                    System.out.print("Enter index to remove: ");
                    System.out.println("Element removed: "+myList.remove(sc.nextInt()));
                    break;
                case 3:
                    System.out.print("Enter index to modify: ");
                    int index = sc.nextInt();
                    System.out.print("Enter new string: ");
                    String value = sc.next();
                    myList.set(index, value);
                    break;
                case 4:
                    System.out.println(myList);
                    break;
                case 5:
                    System.out.println("Exit");
                    break;
                default: System.out.println("Invalid choice!");
            }
        }
        while(choice!=5);
    }
}