Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CS3240 - Generics L. Grewe 2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of.

Similar presentations


Presentation on theme: "1 CS3240 - Generics L. Grewe 2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of."— Presentation transcript:

1

2 1 CS3240 - Generics L. Grewe

3 2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of data; instead, they operate over a homogeneous set, where the set type is defined at declaration. Data Structures that contain data (such as lists) are not defined to operate over a specific type of data; instead, they operate over a homogeneous set, where the set type is defined at declaration. Helps with Reusability (no longer need multiple data structures to hold different types of data) Helps with Reusability (no longer need multiple data structures to hold different types of data) Helps control run-time errors if you instead could have data structures containing different (heterogeneous) kinds of data. Helps control run-time errors if you instead could have data structures containing different (heterogeneous) kinds of data.

4 3 Concept in other languages e.g. C++ e.g. C++ In C++, would write generic stack class using templates template class Stack { private: t data; Stack * next; public: void push (t* x) { … } t* pop ( ) { … } t* pop ( ) { … }};

5 4 Java Generic Programming Java has class Object Java has class Object Supertype of all object typesSupertype of all object types This allows “subtype polymorphism”This allows “subtype polymorphism” Can apply operation on class T to any subclass S <: T Can apply operation on class T to any subclass S <: T Java 1.0 – 1.4 did not have generics Java 1.0 – 1.4 did not have generics No parametric polymorphismNo parametric polymorphism Many considered this the biggest deficiency of JavaMany considered this the biggest deficiency of Java Java type system does not let you “cheat” Java type system does not let you “cheat” Can cast from supertype to subtypeCan cast from supertype to subtype Cast is checked at run timeCast is checked at run time

6 5 Run-Time Error without Generics Example from sun.java.com: In the first example (lines 13 to 20), you might believe you're working with a list of Integer objects, when in reality it's a list of Strings. In the second example (lines 11 and 22 to 27), you might think you're working with a homogenous set of String, but this is a heterogeneous set of both String and Integer elements. So unless you create a new list subclass for every element type (which would undermine the advantages of OO reuse), there's no way to statically constrain the list to a set of homogeneous elements. And in this simple example, the errors are fairly easy to catch. In a bigger program, you'd have even bigger problems. Example from sun.java.com: In the first example (lines 13 to 20), you might believe you're working with a list of Integer objects, when in reality it's a list of Strings. In the second example (lines 11 and 22 to 27), you might think you're working with a homogenous set of String, but this is a heterogeneous set of both String and Integer elements. So unless you create a new list subclass for every element type (which would undermine the advantages of OO reuse), there's no way to statically constrain the list to a set of homogeneous elements. And in this simple example, the errors are fairly easy to catch. In a bigger program, you'd have even bigger problems. 1. 2. List stringList = new LinkedList(); 3. List integerList = new LinkedList(); 4. 5. integerList.add(new Integer(1)); 6. integerList.add(new Integer(2)); 7. 8. stringList.add(new String("I am a String")); 9. 10. // Nothing constrains the elements to a homogeneous set. 11. stringList.add(new Integer(1)); 12. 13. Iterator listIterator = integerList.iterator(); 14. 15. // Compiler unaware of the list's return type and the illegal cast. 16. // Developer meant to iterate through the string list. 17. while(listIterator.hasNext()) { 18. 19. // Illegal cast caught at runtime. 20. String item = (String)listIterator.next(); 21. } 22. 23. listIterator = stringList.iterator(); 24. // No guarantee of homogeneous containers. 25. while (listIterator.hasNext()) { 26. // fail at runtime due to heterogeneous set 27. String item = (String)listIterator.next(); 28. } 29. 1. 2. List stringList = new LinkedList(); 3. List integerList = new LinkedList(); 4. 5. integerList.add(new Integer(1)); 6. integerList.add(new Integer(2)); 7. 8. stringList.add(new String("I am a String")); 9. 10. // Nothing constrains the elements to a homogeneous set. 11. stringList.add(new Integer(1)); 12. 13. Iterator listIterator = integerList.iterator(); 14. 15. // Compiler unaware of the list's return type and the illegal cast. 16. // Developer meant to iterate through the string list. 17. while(listIterator.hasNext()) { 18. 19. // Illegal cast caught at runtime. 20. String item = (String)listIterator.next(); 21. } 22. 23. listIterator = stringList.iterator(); 24. // No guarantee of homogeneous containers. 25. while (listIterator.hasNext()) { 26. // fail at runtime due to heterogeneous set 27. String item = (String)listIterator.next(); 28. } 29.

7 6 Can generics help this problem With generics, you achieve polymorphic behavior similar to the previous code, but with strong static type-checking; the compiler knows that the two lists are different because they contain different elements, and these lists are guaranteed to contain only a homogeneous set of elements. With generics, you achieve polymorphic behavior similar to the previous code, but with strong static type-checking; the compiler knows that the two lists are different because they contain different elements, and these lists are guaranteed to contain only a homogeneous set of elements.

8 7 Previous Example with Generics As you can see from comments in the code, all the errors are caught at compile time. Don't worry about the syntax for now -- we'll cover that shortly. As you can see from comments in the code, all the errors are caught at compile time. Don't worry about the syntax for now -- we'll cover that shortly. In comparing the two examples, you should notice that additional type information is included in the generics code, which directs the compiler as to what type each container should contain. 1. 2. import java.util.LinkedList; 3. import java.util.Collections; 4. import java.util.Iterator; 5. 6. public class genericsExample2{ 7. 8. static public void main(String[] args) { 9. LinkedList stringList = new LinkedList (); 10. LinkedList integerList = new LinkedList (); 11. 12. integerList.add(new Integer(1)); 13. integerList.add(new Integer(2)); 14. 15. stringList.add(new String("I am a String")); 16. stringList.add(new Integer(1)); // causes a compilation error 17. 18. In comparing the two examples, you should notice that additional type information is included in the generics code, which directs the compiler as to what type each container should contain. 1. 2. import java.util.LinkedList; 3. import java.util.Collections; 4. import java.util.Iterator; 5. 6. public class genericsExample2{ 7. 8. static public void main(String[] args) { 9. LinkedList stringList = new LinkedList (); 10. LinkedList integerList = new LinkedList (); 11. 12. integerList.add(new Integer(1)); 13. integerList.add(new Integer(2)); 14. 15. stringList.add(new String("I am a String")); 16. stringList.add(new Integer(1)); // causes a compilation error 17. 18.

9 8 /* genericsExample2.java:16: cannot resolve symbol 19. ** symbol : method add (java.lang.Integer) 20. */ 21. 22. Iterator listIterator = integerList.iterator(); 23. String item; 24. while(listIterator.hasNext()) { 25. item = listIterator.next(); // causes a compilation error 26. 27. /* genericsExample2.java:25: incompatible types 28. ** found : java.lang.Integer 29. ** required: java.lang.String 30. */ 31. } 32. 33. listIterator = stringList.iterator(); // causes a compilation error 34. 35. /* genericsExample2.java:33: incompatible types 36. ** found : java.util.Iterator 37. ** required: java.util.Iterator 38. */ 39. // the iterator is guaranteed to be homogeneous 40. while (listIterator.hasNext()) { 41. item = listIterator.next(); 42. 43. /* genericsEx2.java:41: incompatible types 44. ** found : java.lang.Integer 45. ** required: java.lang.String 46. */ 47. } 48. } // main 49. } // class genericsExample2 /* genericsExample2.java:16: cannot resolve symbol 19. ** symbol : method add (java.lang.Integer) 20. */ 21. 22. Iterator listIterator = integerList.iterator(); 23. String item; 24. while(listIterator.hasNext()) { 25. item = listIterator.next(); // causes a compilation error 26. 27. /* genericsExample2.java:25: incompatible types 28. ** found : java.lang.Integer 29. ** required: java.lang.String 30. */ 31. } 32. 33. listIterator = stringList.iterator(); // causes a compilation error 34. 35. /* genericsExample2.java:33: incompatible types 36. ** found : java.util.Iterator 37. ** required: java.util.Iterator 38. */ 39. // the iterator is guaranteed to be homogeneous 40. while (listIterator.hasNext()) { 41. item = listIterator.next(); 42. 43. /* genericsEx2.java:41: incompatible types 44. ** found : java.lang.Integer 45. ** required: java.lang.String 46. */ 47. } 48. } // main 49. } // class genericsExample2

10 9 public class OldBox { Object data; public OldBox(Object data) { this.data = data; } public Object getData() { return data; } OldBox intBox = new OldBox(42); int x = (Integer) intBox.getData(); OldBox strBox = new OldBox(“Hi”); String s = (String) strBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; ClassCastException! Compiles but fails at runtime ANOTHER Example of Problem without Generics: Cast Exceptions at Runtime

11 10 public class IntBox { Integer data; public IntBox(Integer data) { this.data = data; } public Integer getData() { return data; } public class StrBox { String data; public StrBox(String data) { this.data = data; } public String getData() { return data; } IntBox intBox = new IntBox(42); int x = intBox.getData(); StrBox strBox = new StrBox(“Hi”); String s = strBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; Errors caught by compiler public class FooBox { Foo data; public FooBox(Foo data) { this.data = data; } public Foo getData() { return data; } Infinite many classes possible Without Generics - NOT A GOOD SOLUTION

12 11 Java Generics: Key Idea Parameterize type definitions Parameterize type definitions Parameterized classes and methodsParameterized classes and methods Provide type safety Provide type safety Compiler performs type checkingCompiler performs type checking Prevent runtime cast errorsPrevent runtime cast errors

13 12 Generics: Parameterized Classes public class OldBox { Object data; public OldBox(Object data) { this.data = data; } public Object getData() { return data; } We want the box to hold a “specific” class – abstractly represented Object does not work as we have seen earlier Solution – parameterize the class definition public class Box { E data; public Box(E data) { this.data = data; } public E getData() { return data; } E refers to a particular type The constructor takes an object of type E, not any object To use this class, E must be replaced with a specific class USING Generics

14 13 How to Use Parameterized Classes public class Box { E data; public Box(E data) { this.data = data; } public E getData() { return data; } Box intBox = new Box (42); int x = intBox.getData();//no cast needed Box strBox = new Box (“Hi”); String s = strBox.getData();//no cast needed Following lines will not compile anymore: String s = (String) intBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; Runtime errors now converted to compile time errors

15 14 When to Use Parameterized Classes Particularly useful for “container” classes Particularly useful for “container” classes Containers hold but do not process dataContainers hold but do not process data All collections framework classes in Java 5.0 and on defined using generics All collections framework classes in Java 5.0 and on defined using generics See the Java API documentationSee the Java API documentation

16 15 Collections now use Generic (see java.util) Generic interface Generic interface Generic class implementing Collection interface Generic class implementing Collection interface class LinkedList implements Collection { protected class Node { protected class Node { A elt; A elt; Node next = null; Node next = null; Node (A elt) { this.elt = elt; } Node (A elt) { this.elt = elt; } }......} interface Iterator { E next(); boolean hasNext(); } interface Collection { public void add (A x); public Iterator iterator (); }

17 16 More Collections Code from java.util public interface List { void add(E x); public interface List { void add(E x); Iterator iterator(); Iterator iterator(); } public interface Iterator { E next(); E next(); boolean hasNext(); boolean hasNext();} LinkedList is in java.util and implements List interface as a Generic Class. HOW TO USE THIS CODE List myIntList = new LinkedList (); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();

18 17 Parameterized Classes: Syntax Note A class can have multiple parameters, e.g: public class Stuff { … } Subclassing parameterized classes allowed, e.g: /* Extending a particular type */ class IntBox extends Box { … } Or /* Extending a parameterized type */ class SpecialBox extends Box { … } SpecialBox is a subclass of Box. /* Following assignment is legal */ Box sb = new SpecialBox (“Hi”);

19 18 Parameterized Classes in Methods A parameterized class is a type just like any other class. It can be used in method input types and return types, e.g: Box aMethod(int i, Box b) { … } If a class is parameterized, that type parameter can be used for any type declaration in that class, e.g: public class Box { E data; public Box(E data) { this.data = data; } public E getData() { return data; } public void copyFrom(Box b) { this.data = b.getData(); } }//We have added an infinite number of types of Boxes //by writing a single class definition

20 19 So Far… Type safety violations Type safety violations Using castsUsing casts Parameterized classes solve this problem Parameterized classes solve this problem Provide type safety Provide type safety Enforced by the compilerEnforced by the compiler Particularly useful for container classes Particularly useful for container classes A parameterized class is another type A parameterized class is another type Next – bounded parameterized classes Next – bounded parameterized classes

21 20 Bounded Parameterized Types Sometimes we want restricted parameterization of classes. We want a box, called MathBox that holds only Number objects. We can’t use Box because E could be anything. We want E to be a subclass of Number. public class MathBox extends Box { public MathBox(E data) { super(data); } public double sqrt() { return Math.sqrt(getData().doubleValue()); }

22 21 Bounded Parameterized Types (Contd.) public class MathBox extends Box { public MathBox(E data) { super(data); } public double sqrt() { return Math.sqrt(getData().doubleValue()); } The syntax means that the type parameter of MathBox must be a subclass of the Number class. We say that the type parameter is bounded. new MathBox (5);//Legal new MathBox (32.1);//Legal new MathBox (“No good!”);//Illegal

23 22 Bounded Parameterized Types (Contd.) Inside a parameterized class, the type parameter serves as a valid type. So the following is valid. public class OuterClass { private class InnerClass { … } … } Syntax note: The syntax is valid even if B is an interface.

24 23 Bounded Parameterized Types (Contd.) Java allows multiple inheritance in the form of implementing multiple interfaces. So multiple bounds may be necessary to specify a type parameter. The following syntax is used then: For instance: interface A { … } interface B { … } class MultiBounds { … }

25 24 Parameterized Methods public class Bar { //Bar is parameterized public T aMethod(T x) { return x; } public static void main(String[] args) { Bar bar = new Bar (); int k = bar.aMethod(5); String s = bar.aMethod("abc"); //Compilation error here } Once Bar object is fixed, we are locked to a specific T.

26 25 Use of Parameterized Methods Adding type safety to methods that operate on different types Adding type safety to methods that operate on different types Return type dependent on input typeReturn type dependent on input type

27 26 Upper Bounded Wildcards in Parameterized Types The following is a PROBLME: Box numBox = new Box (31); Compiler comes back with an “Incompatible Type” error message. This is because numBox can hold only a Number object and nothing else, not even an object of type Integer which is a subclass of Number. The type of numBox we desire is “a Box of any type which extends Number ”. Box numBox = new Box (31); SOLUTION

28 27 Upper Bounded Wildcards in Parameterized Types (Contd.) public class Box { public void copyFrom(Box b) { this.data = b.getData(); } //We have seen this earlier //We can rewrite copyFrom() so that it can take a box //that contains data that is a subclass of E and //store it to a Box object public class Box { public void copyFrom(Box b) { this.data = b.getData();//b.getData() is a //subclass of this.data } is called “upper bounded wildcard” because it defines a type that is bounded by the superclass E.

29 28 Lower Bounded Wildcards in Parameterized Types Suppose we want to write copyTo() that copies data in the opposite direction of copyFrom(). copyTo() copies data from the host object to the given object. This can be done as: public void copyTo(Box b) { b.data = this.getData(); } Above code is fine as long as b and the host are boxes of exactly same type. But b could be a box of an object that is a superclass of E. This can be expressed as: public void copyTo(Box b) { b.data = this.getData(); //b.data() is a superclass of this.data() } is called a “lower bounded wildcard” because it defines a type that is bounded by the subclass E.

30 29 Unbounded Wildcards Use unbounded wildcards when any type parameter works. is used to specify unbounded wildcards. The following are legal statements. Box b1 = new Box (31); Box b2 = new Box (“Hi”); b1 = b2; Wildcard capture: The compiler can figure out exactly what type b1 is above from the right hand side of the assignments. This “capturing” of type information means: 1. The type on the left hand doesn’t need to be specified. 2. The compiler can do additional type checks because it knows the type of b1.

31 30 Conclusion Java generics Java generics Parameterized classes and methodsParameterized classes and methods Type safetyType safety Syntax and semantics through examplesSyntax and semantics through examples


Download ppt "1 CS3240 - Generics L. Grewe 2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of."

Similar presentations


Ads by Google