Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Generics, Type Safety, and Dynamic Data Structures.

Similar presentations


Presentation on theme: "1 Generics, Type Safety, and Dynamic Data Structures."— Presentation transcript:

1 1 Generics, Type Safety, and Dynamic Data Structures

2 2 Reminders No classes, labs, recitations next week (gobble gobble) –Consulting hours – Monday only Project 8 (the final one!) is out –start early –Milestone due 11/28 –Final project due 12/5 Armand's Discussion section –Cancelled next week

3 3 Project 7 Design Use object oriented design! –Load method should handle much of the labyrinth processing to make rest of methods easier char[][] and String[] insufficient – still need to process structure of labyrinth later on in every other method (ouch!) Organize information in classes –Labyrinth classes (pros/cons?) –Cell classes (pros/cons?) –Wall classes (pros/cons?)

4 4 Today’s Recitation Collections Java generics –Parameterized classes and methods –Compiler provides type safety Syntax and semantics –Examples Generics Examples

5 5 Collections Collection –Serves as a repository for other objects Array, LinkedList, etc. Java Collections Framework –Provides a unified interface for working with collections

6 6 Java Collections Framework Interfaces –List Most basic collection –Set No Duplicates –SortedSet No Duplicates Sorted order –Map Key, value pairs –SortedMap Key, value pairs Sorted Order Implementations –ArrayList An expandable array –Vector An expandable array –Stack FILO –TreeMap A Map Sorted …

7 7 Collection Design: Keep collections general so that they can hold any type of object Java 5.0 provides generics –Allows type of collection to be established upon instantiation

8 8 Queues Java provides a Queue interface –FIFO data structure As a linked list As an array –Methods boolean offer(E o)// insert element to end of queue E peek()// retreive front element of queue E element()// same as peek, but with exceptions E poll()// remove and return front element of queue E remove()// same as poll, but with exceptions

9 9 Building Your Own List Node class –Item –Next pointer Type unsafe –Class Object supports any class type –Should use parameterized type! public class Node { private Object data; private Node next; public Node(Object data, Node next) { this.data = data; this.next = next; } public void setNext(Node next) { this.next = next; } public void setData(Object data) { this.data = data; } public Node getNext() { return next; } public Object getData() { return data; }

10 10 Java Generics: Key Idea Parameterize type definitions –Parameterized classes and methods Provide type safety –Compiler performs type checking –Prevent runtime cast errors

11 11 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 Cast Exceptions at Runtime

12 12 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 Naïve Solution

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

14 14 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 15 When to Use Parameterized Classes Particularly useful for “container” classes –Containers hold but do not process data All collections framework classes in Java 5.0 defined using generics –See the Java 5.0 API documentation

16 16 Parameterized Classes: Syntax 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” );

17 17 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

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

19 19 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

20 20 Parameterized Methods Consider the following class: public class Foo { //Foo is not parameterized public T aMethod( T x ) { //will not compile without //to indicate that this is a //parameterized method. return x; } public static void main( String[] args ) { Foo foo = new Foo(); int k = foo.aMethod( 5 ); String s = foo.aMethod( "abc" ); } Fix foo and vary parameter to aMethod()‏ 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.

21 21 Generics Examples Stack HashMap List

22 22 Stack Using Generics Without Generics class Stack { void push( Object o ) {... } Object pop() {... }... } String s = "Hello"; Stack st = new Stack();... st.push( s );... s = (String) st.pop(); With Generics class Stack { void push( A a ) {... } A pop() {... }... } String s = "Hello"; Stack st = new Stack (); st.push( s );... s = st.pop();

23 23 Collections Example HashMap sumnerFavFive = new HashMap (); sumnerFavFive.put(1, “Magic Labyrinths”); sumnerFavFive.put(2, “Happy Dogs”); sumnerFavFive.put(3, “Blue Beanies”); sumnerFavFive.put(4, “Huzzah!”); sumnerFavFive.put(5, “CS180 Students”); String SumnerFavorite = sumnerFavFive.get(1); Note: Hashmap_1.4 hm => Hashmap_1.5

24 24 List Using Generics List ys = new LinkedList (); ys.add( "zero" ); List > yss; yss = new LinkedList >(); yss.add( ys ); String y = yss.iterator().next().iterator().next(); // Compile-time error – much better! Integer z = ys.iterator().next();

25 25 Quiz Given the following class signature, what type of objects can the parameterized type T support? public class Quiz > {…}


Download ppt "1 Generics, Type Safety, and Dynamic Data Structures."

Similar presentations


Ads by Google