Generics

21
Generics 1 Generics Parametrized classes and methods

description

Generics. Parametrized classes and methods. 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”. - PowerPoint PPT Presentation

Transcript of Generics

Page 1: Generics

1Generics

Generics

Parametrized classes and methods

Page 2: Generics

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”

Page 3: Generics

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

Page 4: Generics

Generics 4

Benefits of generics

• Making code better– Compile time: Compiler discovers wrong uses

of types.– Runtime: No ClassCastException

• Making code more flexible– Generic classes can be instantiated with

different types.

Page 5: Generics

Generics 5

Type inference - the ”diamond”Java 7 feature

• Java 6– List<String> someList = new ArrayList<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 ♦

Page 6: Generics

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>();

Page 7: Generics

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

Page 8: Generics

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

Page 9: Generics

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.

Page 10: Generics

Generics 10

Raw types

• The raw types are the generic types, but without a specified actual type– ArrayList, Collection, Catalog

Page 11: Generics

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

Page 12: Generics

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://download.oracle.com/javase/7/docs/api/java/util/Collection.html

Page 13: Generics

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)• 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

• http://download.oracle.com/javase/7/docs/api/java/util/Collection.html

Page 14: Generics

Generics 14

Generics methods

• Methods (static and non-static) can be generic– The class needs not be generic.

• Syntax– <T> T method(T element) { …}

• Most often with static methods• Example

– <T> List<T> Collections.synchronizedList(List<T> list)

• http://download.oracle.com/javase/7/docs/api/java/util/Collections.html

Page 15: Generics

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());

Page 16: Generics

Generics 16

Bounded wildcards• ? extends T upper bound

– Some type that is a subtype of T• Or T itself

• ? super T lower bound– Some type that is a super type of T

• Or T itself

• The “Get and Put Principle”– Use wildcard with extends

• When you want to get values out of a structure

– Use wildcard with super• When you want to put values into a structure

Page 17: Generics

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.

Page 18: Generics

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

Page 19: Generics

Generics 19

Other programming languages

• C++ templates– Code is expanded – No erasures (no wildcards): Code bloat

Page 20: Generics

Generics 20

References

• Sun Microsystems The Java Tutorial– Generics

http://download.oracle.com/javase/tutorial/extra/generics/index.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.

Page 21: Generics

Generics 21

More references

• Naftalin & Wadler Java Generics and Collections, O’Reilly 2007– Page 1-150 is about

generics

• Niemeyer & Knudsen Learning Java, 3rd edition, O’Reilly 2005– 8. Generics, page 214-248