Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.

Similar presentations


Presentation on theme: "1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand."— Presentation transcript:

1 1 Chapter 21 Generics

2 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand why generic types can improve reliability and robustness (§21.3). F To declare and use generic methods and bounded generic types (§21.4). F To use raw types for backward compatibility (§21.5). F To know wildcard types and understand why they are necessary (§21.6). F To understand that all instances of a generic class share the same runtime class file (§21.7). F To convert legacy code using JDK 1.5 generics (§21.8). F To design and implement a generic matrix class (§21.9).

3 Example: Pre_Java5 3

4 See these warnings before? 4 Warnings from last compilations uses unchecked or unsafe operations Recompile with –Xlint unchecked for details

5 5 Why Do You Get a Warning? public class TestArrayList { public static void main(String[] args) { // Create a list to store cities java.util.ArrayList cityList = new java.util.ArrayList(); // Add some cities in the list cityList.add("London"); } To understand the compile warning on this line, you need to learn JDK 1.5 generics.

6 6 ArrayList public ArrayList() Constructs an empty list with an initial capacity of ten. add public boolean add(E e) Appends the specified element to the end of this list.E Specified by:add in interface Collection Specified by:add in interface List Overrides:add in class AbstractList Parameters:e - element to be appended to this list Returns:true (as specified by Collection.add(E))addCollectionEaddListEaddAbstractListECollection.add(E)

7 7 Generic Type Generic Instantiation Runtime error Compile error Improves reliability Restricts to type Date

8 8 Generic ArrayList in JDK 1.5

9 9 Fix the Warning in BJ_Java5 import java.util.*; public class TestArrayListNew { public static void main(String[] args) { ArrayList cityList = new ArrayList (); // Add some cities in the list cityList.add("London"); } } Tells compiler that Strings are expected. No compile warning on this line.

10 10 No Casting Needed – Boxing and Unboxing ArrayList list = new ArrayList (); list.add(5.5); // 5.5 is automatically converted to new Double(5.5) list.add(3.0); // 3.0 is automatically converted to new Double(3.0) Double doubleObject = list.get(0); // No casting is needed double d = list.get(1); // Automatically converted to double

11 11 Declaring Generic Classes and Interfaces BJ_GenericStack

12 To print elements of different types Before Java5 12 public class PreJava5MethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; PreJava5MethodDemo.print(integers); PreJava5MethodDemo.print(strings); } // Provide two overloaded methods public static void print(Integer[] list) { //... } public static void print(String[] list) { //... } }

13 To print elements of different types From Java5 with Generic Methods 13 public class GenericMethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; GenericMethodDemo. print(integers); GenericMethodDemo. print(strings); } public static void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

14 14 Generic Methods public static void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }// versus public static void print(Object[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

15 Can I specify the type as say ? 15 public class GenericMethodDemoF { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York", "Austin"}; GenericMethodDemo. print(integers); GenericMethodDemo. print(strings); } public static void print(F[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

16 Can I specify subtypes? 16 Suppose we want to restrict to Circle and Rectangle objects only in class BoundedTypeDemo

17 17 Bounded Generic Type public static void main(String[] args ) { Rectangle rectangle = new Rectangle(2, 2); Circle9 circle = new Circle9(2); System.out.println("Same area? " + equalArea(rectangle, circle)); } // Want to restrict to subclasses of GeometricObject public static boolean equalArea(E object1, E object2) { return object1.findArea() == object2.findArea(); }

18 Bounded Generic Type F See BJ_BoundedType 18

19 19 Raw Type and Backward Compatibility // raw type GenericStack stack = new GenericStack(); This is roughly equivalent to GenericStack stack = new GenericStack ();

20 20 Raw Type: Compile? Run? Safe? Why? Max.max("Welcome", 23); // Max.java: Find a maximum object public class Max { /** Return the maximum between two objects */ public static Comparable max(Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } // see also the code in BJ_Max around compareTo public static void main(String[] args) { System.out.println("max is " + Max.max("Welcome", 23)); }

21 Runtime Exception on running class Max: 21 Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at java.lang.String.compareTo(String.java:92) at Max.max(Max.java:9) at Max.main(Max.java:17)

22 22 Make it Safe – See class BJ_Max1 Max.max("Welcome", 23); // Max1.java: Find a maximum object public class Max1 { /** Return the maximum between two objects */ public static > E max(E o1, E o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; }

23 23 Compilation error instead

24 24 Wildcards WildCardDemo1 Why wildcards are necessary? See this example. ? unbounded wildcard ? Extends T bounded wildcard ? Super T lower bound wildcard: WildCardDemo2WildCardDemo3

25 25

26 WildCardDemo1 26 public class WildCardDemo1 { public static void main(String[] args ) { GenericStack intStack = new GenericStack (); intStack.push(1); // 1 is autoboxed into new Integer(1) intStack.push(2); intStack.push(-2); System.out.println("The max number is " + max(intStack)); }

27 WildCardDemo1.max 27 /** Find the maximum in a stack of numbers */ public static double max(GenericStack stack) { /** intStack is an instance of GenericStack but NOT GenericStack */ double max = stack.pop().doubleValue(); // initialize max while (!stack.isEmpty()) { double value = stack.pop().doubleValue(); if (value > max) max = value; } return max; }

28 28 /** means any subtype of Object and associated with GenericStack */ public class WildCardDemo2 { public static void main(String[] args ) { GenericStack intStack = new GenericStack (); intStack.push(1); // 1 is autoboxed into new Integer(1) intStack.push(2); intStack.push(-2); print(intStack); System.out.println(); } // Print objects and empties the stack public static void print(GenericStack stack) { /** 1st form: ^^^ unbounded wildcard, same as ? extends Object */ while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); }

29 29 /** means any subtype of Object and associated with GenericStack */ public class WildCardDemo2A { public static void main(String[] args ) { GenericStack intStack = new GenericStack (); intStack.push(1); // 1 is autoboxed into new Integer(1) intStack.push(2); intStack.push(-2); print(intStack); System.out.println(); } // Print objects and empties the stack public static void print(GenericStack stack) { /** 2nd form: ^^^^^^^^^^^^^^^^^^ bounded wildcard, Number or subtype */ while (!stack.isEmpty()) { System.out.print(stack.pop() + " "); }

30 WildCardDemo3 30 /** represents type T or supertype of T */ public class WildCardDemo3 { public static void main(String[] args) { GenericStack stack1 = new GenericStack (); GenericStack stack2 = new GenericStack (); stack2.push("Java"); stack2.push(2); stack1.push("Sun"); add(stack1, stack2); WildCardDemo2.print(stack2); System.out.println(); }

31 GenericStack 31 /** Pop each element of stack1 and push it on stack2 */ public static void add( GenericStack stack1, GenericStack stack2) { /** 3rd form ^^^^^^^^^^^ type T or super type of T. Here Object is super type of String will compile fine.*/ while (!stack1.isEmpty()) stack2.push(stack1.pop()); }

32 Watch out F What if we replace F GenericStack stack2) { F in line 15 of GenericStack3 by F GenericStack stack2) { F ? F Reasoning: Only Strings are in stack1, but String is subclass of Object. Must we declare stack2 as GenericStack ? 32

33 Answer – YES! F Change the code in WildCardDemo3A F and compile F Compiler error: F add( GenericStack, GenericStack ) in F WildCardDemo3A cannot be applied to F (GenericStack stack1, F GenericStack stack2) F Compiler usually checks syntax – pattern matching. 33

34 34 Generic Types and Wildcard Types The above diagram in Figure 21.6 confusing

35 35 Erasure and Restrictions on Generics Implementation of Generics - type erasure. - Compiler uses the generic type information to compile the code, but erases it afterwards. - Hence generic information is not available at run time. - Reason: To enable the generic code to be backward-compatible with the legacy code that uses raw types.

36 36 Compile Time Checking Example: -Compiler checks whether generics is used correctly for the code in (a); -Translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type.

37 37 Important Facts It is important to note that a generic class is shared by all its instances regardless of its actual generic type. GenericStack stack1 = new GenericStack (); GenericStack stack2 = new GenericStack (); Although GenericStack and GenericStack are two types, but there is only one class GenericStack loaded into the JVM.

38 38 Restrictions on Generics F Restriction 1: Cannot Create an Instance of a Generic Type. (i.e., new E()). F Restriction 2: Generic Array Creation is Not Allowed. (i.e., new E[100]). F Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context. F Restriction 4: Exception Classes Cannot be Generic.

39 Restriction 1 F Restriction 1: Cannot Create an Instance of a Generic Type. F E Object = new E(); // wrong F Reason: new E(); is run at runtime but the generic type E is not available at runtime. 39

40 Restriction 2 F Restriction 2: Generic Array Creation is Not Allowed. F E[] elements = new E[100]; // wrong F There is no E class F Circumvent: F E[] elements = (E[]) new Object[100]; F But warning is unavoidable 40

41 Restriction 2 example 41 // To instantiate an array of 10 array lists ArrayList [] list = new ArrayList [10] //wrong ArrayList [] list = (ArrayList []) new ArrayList[10]; // to circumvent // But still compiler warning

42 Restriction 3 F Restriction 3: A Generic Type Parameter of a Class Is Not Allowed in a Static Context. F Reason: All instance of a generic class have the same runtime class, static (class) variables and method are shared by all instances. Hence it is illegal to refer to a generic type parameter for a class in static method or field. 42

43 Restriction 3 F public class Teste { F public static void m(E obj1) //illegal F } –public static E obj; // illegal } 43

44 Restriction 4 F Restriction 4: Exception Classes Cannot be Generic. F Reason: A generic class may not extend java.util.Throwable 44

45 Restriction 4 45 public class MyException extends Exception { - - - } // illegal try {... } Catch (MyException ex) {... } /* JVM would have to match the type in runtime but the type is not available at runtime. */

46 Review BJ_TestArrayList and BJ_GenericSort F See BJ_TestArrayListNew –Compare TestArrayList – with unchecked warnings –TestArrayListNew – no warnings needed F See BJ_GenericSortNew –Compare TestGenericSort – with unchecked warnings –And TestGenericSortNew – no warnings needed 46


Download ppt "1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand."

Similar presentations


Ads by Google