Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.

Similar presentations


Presentation on theme: "Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of."— Presentation transcript:

1 Generics1 Parametrized classes and methods

2 Generics2 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”

3 Generics3 No more type casts Before generics List 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 generics List = new ArrayList (); 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

4 Generics4 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.

5 Type inference - the ”diamond” Java 7 feature Java 6 –List someList = new ArrayList (); Java 7 –List someList = new ArrayList<>(); –Map > multiMap = new HashMap<>(); –The compiler will automatically “calculate” there type of the right hand side object –<> is supposed to look like a diamond ♦ Generics5

6 6 Defining and using your own generic class Definition public class Catalog { List catalog = new ArrayList (); public boolean add(T element) { catalog.add(element); } Usage Catalog bc = new Catalog (); Catalog bookCatalog = new Catalog ();

7 Generics7 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 is “erased” to Catalog

8 Generics8 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 list = new ArrayList (); System.out.println("list type: " + list.getClass()); Writes ArrayList, nothing said about String. if (list instanceof ArrayList ) … Illegal, since is not present at run-time if (list instanceof ArrayList) … Legal

9 Generics9 Relationships among generics Object is a super type of String. ArrayList is not a super type of ArrayList –Object and String are erased at compile time. –Runtime system has no knowledge of the types.

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

11 Generics11 An example: Using raw types to break “security” public static String loophole(Integer x) { List ys = new LinkedList (); 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

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

13 Generics13 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 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

14 Generics14 Generics methods Methods (static and non-static) can be generic –The class needs not be generic. Syntax – T method(T element) { …} Most often with static methods Example – List Collections.synchronizedList(List list) http://download.oracle.com/javase/7/docs/api/java/util/Collections.html

15 Generics15 Wild cards with lower bounds Most often used with generic methods Examples from java.util.Collections –static void fill(List 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 list; –… –Collections.fill(list, new JButton());

16 Generics16 Bounded wildcards ? extends Tupper bound –Some type that is a subtype of T Or T itself ? super Tlower 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

17 Generics17 Comparing and sorting The class java.util.Collections has static methods for sorting elements in lists – > void sort(List list)ComparableList – void sort(List list, Comparator c)ListComparator –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.

18 Generics18 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

19 Generics19 Other programming languages C++ templates –Code is expanded –No erasures (no wildcards): Code bloat

20 Generics20 References Sun Microsystems The Java Tutorial –Generics http://download.oracle.com/javase/tutorial/extra/generics/index.html 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.pdfhttp://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf –Also known as the ”Generics Tutorial” –Thorough introduction to generics.

21 Generics21 More references Naftalin & Wadler Java Generics and Collections, O’Reilly 2007 –Page 1-150 is about generics Niemeyer & Knudsen Learning Java, 3 rd edition, O’Reilly 2005 –8. Generics, page 214-248


Download ppt "Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of."

Similar presentations


Ads by Google