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 not typed To 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 –Runtime: No ClassCastException –Compile time: Compiler discovers wrong uses of types. Making code more flexible –Generic classes can be instantiated with different types.

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

6 Generics6 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

7 Generics7 Erasure (2) Types are checked and removed (erased) –No generics in the JVM. All instances of a generics class has 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

8 Generics8 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. –Example http://java.sun.com/docs/books/tutorial/java/javaOO/genrels.html

9 Generics9 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 Collection c = method.returnsCollOfSomething –Generates “unchecked warning”

10 Generics10 An example: Using raw types to break “security” public String loophole(Integer x) { List ys = new LinkedList (); List xs = ys; xs.add(x); // Compile time: warning: unchecked call return ys.get(0); } We used xs as an oldfashioned (untyped) alias to ys. Using xs we were able to insert an Integer into ys. Generally –Don’t ignore warnings. –Avoid untyped collections. From: Gilad Bracha: Generics in the Java Programming Language, page 12

11 Generics11 Wildcard types Yet another feature to solve the problems with relationships among generics. New syntax: ? Example –http://java.sun.com/docs/books/tutorial/java/javaOO/genwildcard. htmlhttp://java.sun.com/docs/books/tutorial/java/javaOO/genwildcard. html –MyClass MyClass of any type Example –Boolean java.util.Collection.containsAll(Collection c) –http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html

12 Generics12 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) http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.ht mlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.ht ml 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

13 Generics13 Generics methods Methods (static and non-static) can be generic Syntax – T method(T element) { …} Most often with static methods Example – List Collections.synchronizedList(List list) http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.ht mlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.ht ml

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

15 Generics15 Bound wildcards ? Extends Tupper bound –Unknown type that is a subtype of T Or T itself ? super Tlower bound –Unknown type that is a super type of T Or T itself

16 Generics16 Comparing and sorting The class java.util.Collections has static methods for ordering 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.

17 Generics17 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 http://java.sun.com/docs/books/tutorial/java/javaOO/genlegacy.html Generics – legacycode.Cat 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

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

19 Generics19 References Sun Microsystems The Java Tutorial –Generics http://java.sun.com/docs/books/tutorial/java/javaOO/generics.html http://java.sun.com/docs/books/tutorial/java/javaOO/generics.html –Easy introduction to generics. 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” –Through introduction to generics.


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