Generics, Type Safety, and Dynamic Data Structures - PowerPoint PPT Presentation

About This Presentation
Title:

Generics, Type Safety, and Dynamic Data Structures

Description:

Labyrinth classes (pros/cons?) Cell classes (pros/cons?) Wall classes (pros/cons?) 4 ... sumnerFavFive.put(1, 'Magic Labyrinths'); sumnerFavFive.put(2, 'Happy Dogs' ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 26
Provided by: anupam7
Category:

less

Transcript and Presenter's Notes

Title: Generics, Type Safety, and Dynamic Data Structures


1
Generics, Type Safety, and Dynamic Data Structures
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
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
Todays Recitation
  • Collections
  • Java generics
  • Parameterized classes and methods
  • Compiler provides type safety
  • Syntax and semantics
  • Examples
  • Generics Examples

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
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
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
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
Building Your Own List
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
  • Node class
  • Item
  • Next pointer
  • Type unsafe
  • Class Object supports any class type
  • Should use parameterized type!

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

11
Cast Exceptions at Runtime
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
12
Naïve Solution
public class StrBox String data public
StrBox( String data ) this.data data
public String getData() return data

public class IntBox Integer data public
IntBox( Integer data ) this.data data
public Integer 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
Infinite many classes possible
13
Parameterized Classes
public class OldBox Object data public
OldBox( Object data ) this.data data
public Object getData() return data

public class BoxltEgt E data public Box( E
data ) this.data data public E
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
  • 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
How to Use Parameterized Classes
public class BoxltEgt E data
public Box( E data ) this.data data
public E getData() return
data
BoxltIntegergt intBox new BoxltIntegergt( 42 ) int
x intBox.getData()//no cast needed BoxltStringgt
strBox new BoxltStringgt( 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
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
Parameterized Classes Syntax
A class can have multiple parameters,
e.g public class StuffltA,B,Cgt
Subclassing parameterized classes allowed,
e.g / Extending a particular type / class
IntBox extends BoxltIntegergt Or / Extending
a parameterized type / class SpecialBoxltEgt
extends BoxltEgt
SpecialBoxltStringgt is a subclass of
BoxltStringgt. / Following assignment is legal
/ BoxltStringgt sb new SpecialBoxltStringgt( Hi
)
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 BoxltStringgt aMethod( int
i, BoxltIntegergt b )
If a class is parameterized, that type parameter
can be used for any type declaration in that
class, e.g public class BoxltEgt E data
public Box( E data ) this.data data
public E getData() return data
public void copyFrom( BoxltEgt b ) this.data
b.getData() //We have added an infinite
number of types of Boxes //by writing a single
class definition
18
Bounded Parameterized Types
Sometimes we want restricted parameterization of
classes. We want a box, called MathBox that holds
only Number objects. We cant use BoxltEgt because
E could be anything. We want E to be a subclass
of Number.
public class MathBoxltE extends Numbergt extends
BoxltNumbergt public MathBox( E data )
super( data ) public double sqrt()
return Math.sqrt( getData().doubleValue() )
19
Bounded Parameterized Types (Contd.)?
public class MathBoxltE extends Numbergt extends
BoxltNumbergt public MathBox( E data )
super( data ) public double sqrt()
return Math.sqrt( getData().doubleValue() )
The ltE extends Numbergt 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 MathBoxltIntegergt( 5 )//Legal new
MathBoxltDoublegt( 32.1 )//Legal new
MathBoxltStringgt( No good! )//Illegal
20
Parameterized Methods
Consider the following class public class Foo
//Foo is not parameterized public ltTgt T
aMethod( T x ) //will not compile without
ltTgt //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" )
public class BarltTgt //Bar is parameterized
public T aMethod( T x ) return x
public static void main( String args )
BarltIntegergt bar new BarltIntegergt()
int k bar.aMethod( 5 ) String s
bar.aMethod( "abc" ) //Compilation error
here
Fix foo and vary parameter to aMethod()?
Once BarltTgt object is fixed, we are locked to a
specific T.
21
Generics Examples
  • Stack
  • HashMap
  • List

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 StackltAgt
  • void push( A a ) ...
  • A pop() ...
  • ...
  • String s "Hello"
  • StackltStringgt st
  • new StackltStringgt()
  • st.push( s )
  • ...
  • s st.pop()


23
Collections Example
  • HashMapltIntger, Stringgt sumnerFavFive
  • new HashMapltIntger, Stringgt()
  • 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 gt Hashmap_1.5ltObject,
    Objectgt

24
List Using Generics
  • ListltStringgt ys new LinkedListltStringgt()
  • ys.add( "zero" )
  • ListltListltStringgtgt yss
  • yss new LinkedListltListltStringgtgt()
  • yss.add( ys )
  • String y yss.iterator().next().iterator().next()
  • // Compile-time error much better!
  • Integer z ys.iterator().next()

25
Quiz
  • Given the following class signature, what type of
    objects can the parameterized type T support?
  • public class QuizltT extends ComparableltTgtgt
Write a Comment
User Comments (0)
About PowerShow.com