The Power Of Generics

Waking up in the morning, deciding what to drink, filling up your cup. Surprisingly! You are leveraging the power of generics.

OMAR ELGABRY
Jan 6, 2017 · 4 min read
Fill your cup with any drink, and Enjoy the power of generics —unsplash

“By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.”

What’s The Problem?

First Try

Second Try

StackOfObjects stack = new StackOfObjects();stack.push(new Apple());
stack.push(new Orange());
Apple a = (Apple) s.pop(); // Run-time error! casting won’t help

Third Try

Generics

A Simple Stack Class

public class Stack {
private Node first = null;

private class Node {
Object item;
Node next;
}

public void push(Object item) { /* … */ }
public Object pop() { /* … */ }
}

A Generic Stack Class

class name<T1, T2, …, Tn> { /* … */ }
public class Stack<Item> {
private Node first = null;

private class Node {
Item item;
Node next;
}

public void push(Item item) { /* … */ }
public Item pop() { /* … */ }
}

Generic Arrays

public class Stack<Item> {
private Item[] s;
private int N = 0;

public Stack(int capacity){
s = new Item[capacity]; // not allowed
}
}
public Stack(int capacity){     
s = (Item[]) new Object[capacity];
}

Naming Conventions

public class Pair<K, V> { /* … */ }

Using Generic Class

Stack<Apple> appleStack   = new Stack<Apple>();
Stack<Orange> orangeStack = new Stack<Orange>();
appleStack.push(new Apple());
orangeStack.push(new Orange());

Type Parameter

Stack<Integer> stack = new Stack<Integer>();

Autoboxing and Unboxing

Stack<Integer> s = new Stack<Integer>();
s.push(17); // equivalent to: s.push(new Integer(17));
int num = s.pop(); // equivalent to: s.pop().intValue();

Type Mismatch Errors

Stack<Apple> stack = new Stack<Apple>();stack.push(new Apple());
stack.push(new Orange()); // Compile-time error
Apple a = s.pop();

Why Use Generics?

OmarElGabry's Blog

This is my freedom area. Don't underestimate it. The devil is in the detail.

OMAR ELGABRY

Written by

Software Engineer. Going to the moon 🌑. When I die, turn my blog into a story.

OmarElGabry's Blog

This is my freedom area. Don't underestimate it. The devil is in the detail.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade