1Generics
Generics
Parametrized classes and methods
Generics 2
What are generics
• Generics are classes or interfaces that can be instantiated with a variety of types.– They have 1 or more formal type parameters– Using a generic you specify an actual type
• Also known as “parametrized types”– Or types with “holes”
Generics 3
No more type casts
Before genericsList myList = new ArrayList();myList.add(“Anders”);…String str = (String)myList.get(0);
– Type casts are generally considered bad since they may fail at runtime• If you add something that is not a string
– myList.add(new Integer(56));
After genericsList<String> = new ArrayList<String> ();myList.add(“Anders”);…String str = myList.get(0);
– myList is now typed • String in this case
– We don’t need type casting.– We cannot add anything but Strings
• myList.add(56); – Does not compile
Generics 4
Benefits of generics
• Making code better– Runtime: No ClassCastException– Compile time: Compiler discovers wrong uses
of types.• Making code more flexible
– Generic classes can be instantiated with different types.
Generics 5
Type inference - the ”diamond”
• Java 7 feature• Java 6
– List<String> someList = new List<String>();• Java 7
– List<String> someList = new ArrayList<>();– Map<T, Set<E>> multiMap = new HashMap<>();– The compiler will automatically “calculate” there
type of the right hand side object– <> is supposed to look like a diamond!?
Generics 6
Defining and using your own generic class
• Definitionpublic class Catalog<T> { List<T> catalog = new ArrayList<T>(); public boolean add(T element) { catalog.add(element); }}
• UsageCatalog<Borrower> bc = new Catalog<Borrower>();Catalog<Book> bookCatalog = new Catalog<Book>();
Generics 7
Erasure
• At compile-time all the types are checked and removed (erased) from the class file.– What is left is called the “raw type”.– The class file has no knowledge of the types.– Example
• Catalog<Borrower> is “erased” to Catalog
Generics 8
Erasure (2)
• Types are checked and removed (erased)– No generics in the JVM.
• All instances of a generics class have the same run-time class
List<String> list = new ArrayList<String>();
System.out.println("list type: " + list.getClass());• Writes ArrayList, nothing said about String.
if (list instanceof ArrayList<String>) …• Illegal, since <String> is not present at run-time
if (list instanceof ArrayList) …• Legal
Generics 9
Relationships among generics
• Object is a super type of String.• ArrayList<Object> is not a super type of
ArrayList<String>– Object and String are erased at compile time.– Runtime system has no knowledge of the
types.
Generics 10
Raw types
• The raw types are the generic types, but without a specified actual type– ArrayList, Collection, Catalog
• Collection is “equal” to Collection<?>– but not Collection<Object>
Generics 11
An example: Using raw types to break “security”
public String loophole(Integer x) { List<String> ys = new LinkedList<String>(); List xs = ys; xs.add(x); return ys.get(0); }
• We used xs as an old-fashioned (un-typed) alias to ys. Using xs we were able to insert an Integer into ys.
• Generally– Avoid un-typed collections.
From: Gilad Bracha: Generics in the Java Programming Language, page 12
Generics 12
Wildcard types
• Yet another feature to solve the problems with relationships among generics.
• New syntax: ?– MyClass<?>
• MyClass of any type
• Example – Boolean java.util.Collection.containsAll(Collection<?>
c)– http://java.sun.com/javase/6/docs/api/java/util/Collections.html
Generics 13
Wild card types with upper bounds
• Sometimes the types cannot be chosen completely free– We have to make sure that the type has certain
features• Example
– Java.util.Collection.addAll(Collection<? extends E> c)• http://java.sun.com/javase/6/docs/api/java/util/Collections.html• Can use any collection of types that extends E (which is the
element type of this Collection• The type is said to have an “upper bound” (in the class
hierarchy)– In this case E
Generics 14
Generics methods
• Methods (static and non-static) can be generic
• Syntax– <T> T method(T element) { …}
• Most often with static methods• Example
– <T> List<T> Collections.synchronizedList(List<T> list)
• http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html
Generics 15
Wild cards with lower bounds
• Most often used with generic methods• Examples from java.util.Collections
– static <T> void fill(List<? super T> list, T obj)• Replaces all of the elements of the specified list with the
specified element. • T is the type of the new object• List must have elements which are super types of T
– T is a lower bound in the object hierarchy• Example
– List<JComponent> list;– …– Collections.fill(list, new JButton());
Generics 16
Bounded wildcards
• ? extends T upper bound– Unknown type that is a subtype of T
• Or T itself
• ? super T lower bound– Unknown type that is a super type of T
• Or T itself
Generics 17
Comparing and sorting
• The class java.util.Collections has static methods for sorting elements in lists– <T extends Comparable<? super T>> void sort(List<T> list) – <T> void sort(List<T> list, Comparator<? super T> c)– This is a lot of syntax!– First sort method orders elements according to the natural order
• int: 1,2,3,4, etc.• String: a, b, c, etc.
– Second sort method orders elements according to the specified comparator
• A comparator compares 2 elements and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Generics 18
Using generics with legacy code
• Legacy code means old code– In this case code written prior to Java 5.0 is considered old
• How do you deal with legacy classes that don’t use generics (but ought to)?– Examples
• Generics – legacycode.Cat.java
• Compiler sends you warnings– … uses unchecked or unsafe operations
• When you call methods on a raw type– … unchecked cast
• When you cast from raw to generic type.– You may have to live with such warnings
• Or change the legacy code
Generics 19
Other programming languages
• C++ templates– Code is expanded – No erasures (no wildcards): Code bloat
Generics 20
References
• Sun Microsystems The Java Tutorial– Generics http://java.sun.com/docs/books/tutorial/java/javaOO/generics.html– Easy introduction to generics.
• Gilad Bracha– http://java.sun.com/docs/books/tutorial/extra/
generics/index.html• Gilad Bracha Generics in the Java
Programming Language, Sun Microsystems 2004– http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf – Also known as the ”Generics Tutorial”– Thorough introduction to generics.
Generics 21
More references
• Niemeyer & Knudsen Learning Java, 3rd edition, O’Reilly 2005– 8. Generics, page 214-248