Last active
December 29, 2015 12:19
-
-
Save rshepherd/7669941 to your computer and use it in GitHub Desktop.
Introduction to Java Generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
public class ParametricPolymorphism { | |
public static void main(String[] args) { | |
// Java Generics are an implementation of parametric polymorphism. They can be complicated subject. | |
// We will only focus on their simple use case with collections (lists, sets, stacks, etc) | |
// Old Java (1.4 and older): | |
ArrayList l1 = new ArrayList(); | |
l1.add("hello"); | |
String s1 = (String) l1.get(0); // Note the cast | |
// New-ish (since 1.5): | |
ArrayList<String> l2 = new ArrayList <String>(); | |
l2.add("hello"); | |
String s2 = l2.get(0); | |
// Why? | |
// Type-safety! The compiler can catch problems | |
// This blows up at runtime | |
NonGenericStack ngStack = new NonGenericStack(); | |
ngStack.push("String"); | |
ngStack.push(123); | |
String str1 = (String) ngStack.pop(); | |
// This is a compile error | |
GenericStack<String> gStack = new GenericStack<String>(); | |
gStack.push("String"); | |
gStack.push(123); // compiler will complain!! | |
String str2 = (String) ngStack.pop(); | |
// We love the compiler. Its purpose in life is to make our lives easier. | |
} | |
static class NonGenericStack { | |
private ArrayList contents = new ArrayList(); | |
public void push(Object element) { | |
contents.add(element); | |
} | |
public Object pop() { | |
int top = contents.size()-1; | |
Object result = contents.get(top); | |
contents.remove(top); | |
return result; | |
} | |
} | |
static class GenericStack<E> { | |
private ArrayList<E> contents = new ArrayList<E>(); | |
public void push(E element) { | |
contents.add(element); | |
} | |
public E pop() { | |
int top = contents.size()-1; | |
E result = contents.get(top); | |
contents.remove(top); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment