1 generics, type safety, and dynamic data structures

25
1 Generics, Type Safety, and Dynamic Data Structures

Post on 20-Dec-2015

220 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 Generics, Type Safety, and Dynamic Data Structures

1

Generics, Type Safety, and Dynamic Data Structures

Page 2: 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

Page 3: 1 Generics, Type Safety, and Dynamic Data Structures

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?)

Page 4: 1 Generics, Type Safety, and Dynamic Data Structures

4

Today’s Recitation

• Collections• Java generics

– Parameterized classes and methods– Compiler provides type safety

• Syntax and semantics – Examples

• Generics Examples

Page 5: 1 Generics, Type Safety, and Dynamic Data Structures

5

Collections

• Collection– Serves as a repository for other objects

• Array, LinkedList, etc.

• Java Collections Framework– Provides a unified interface for working

with collections

Page 6: 1 Generics, Type Safety, and Dynamic Data Structures

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

Page 7: 1 Generics, Type Safety, and Dynamic Data Structures

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

Page 8: 1 Generics, Type Safety, and Dynamic Data Structures

8

Queues

• Java provides a Queue interface– FIFO data structure

• As a linked list• As an array

– Methodsboolean 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

Page 9: 1 Generics, Type Safety, and Dynamic Data Structures

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;

}}

Page 10: 1 Generics, Type Safety, and Dynamic Data Structures

10

Java Generics: Key Idea

• Parameterize type definitions– Parameterized classes and methods

• Provide type safety– Compiler performs type checking– Prevent runtime cast errors

Page 11: 1 Generics, Type Safety, and Dynamic Data Structures

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

Page 12: 1 Generics, Type Safety, and Dynamic Data Structures

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

Page 13: 1 Generics, Type Safety, and Dynamic Data Structures

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

Page 14: 1 Generics, Type Safety, and Dynamic Data Structures

14

How to Use Parameterized Classes

public class Box<E> { E data; public Box( E data ) { this.data = data; } public E getData() { return data; } }

Box<Integer> intBox = new Box<Integer>( 42 );int x = intBox.getData();//no cast needed

Box<String> strBox = new Box<String>( “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 tocompile time errors

Page 15: 1 Generics, Type Safety, and Dynamic Data Structures

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

Page 16: 1 Generics, Type Safety, and Dynamic Data Structures

16

Parameterized Classes: Syntax

A class can have multiple parameters, e.g:

public class Stuff<A,B,C> { … }

Subclassing parameterized classes allowed, e.g:/* Extending a particular type */class IntBox extends Box<Integer> { … }Or/* Extending a parameterized type */class SpecialBox<E> extends Box<E> { … }

SpecialBox<String> is a subclass of Box<String>./* Following assignment is legal */Box<String> sb = new SpecialBox<String>( “Hi” );

Page 17: 1 Generics, Type Safety, and Dynamic Data Structures

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<String> aMethod( int i, Box<Integer> 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> { E data; public Box( E data ) { this.data = data; } public E getData() { return data; } public void copyFrom( Box<E> b ) { this.data = b.getData(); }}//We have added an infinite number of types of Boxes //by writing a single class definition

Page 18: 1 Generics, Type Safety, and Dynamic Data Structures

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<E> because E could be anything.We want E to be a subclass of Number.

public class MathBox<E extends Number> extends Box<Number> { public MathBox( E data ) { super( data ); } public double sqrt() { return Math.sqrt( getData().doubleValue() ); }}

Page 19: 1 Generics, Type Safety, and Dynamic Data Structures

19

Bounded Parameterized Types (Contd.)

public class MathBox<E extends Number> extends Box<Number> { public MathBox( E data ) { super( data ); } public double sqrt() { return Math.sqrt( getData().doubleValue() ); }}

The <E extends Number> 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<Integer>( 5 );//Legalnew MathBox<Double>( 32.1 );//Legalnew MathBox<String>( “No good!” );//Illegal

Page 20: 1 Generics, Type Safety, and Dynamic Data Structures

20

Parameterized MethodsConsider the following class:public class Foo {//Foo is not parameterized public <T> T aMethod( T x ) { //will not compile without <T> //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<T> {//Bar is parameterized public T aMethod( T x ) { return x; } public static void main( String[] args ) { Bar<Integer> bar = new Bar<Integer>(); int k = bar.aMethod( 5 ); String s = bar.aMethod( "abc" ); //Compilation error here }}

Once Bar<T> object is fixed, we are locked to a specific T.

Page 21: 1 Generics, Type Safety, and Dynamic Data Structures

21

Generics Examples

• Stack• HashMap• List

Page 22: 1 Generics, Type Safety, and Dynamic Data Structures

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<A> { void push( A a ) { ... } A pop() { ... } ...}

String s = "Hello";Stack<String> st = new Stack<String>();st.push( s );...s = st.pop();

Page 23: 1 Generics, Type Safety, and Dynamic Data Structures

23

Collections Example

HashMap<Intger, String> sumnerFavFive = new HashMap<Intger, String>();

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<Object, Object>

Page 24: 1 Generics, Type Safety, and Dynamic Data Structures

24

List Using Generics

List<String> ys = new LinkedList<String>();ys.add( "zero" );List<List<String>> yss;yss = new LinkedList<List<String>>();yss.add( ys );String y = yss.iterator().next().iterator().next();

// Compile-time error – much better!Integer z = ys.iterator().next();

Page 25: 1 Generics, Type Safety, and Dynamic Data Structures

25

Quiz

• Given the following class signature, what type of objects can the parameterized type T support?

public class Quiz<T extends Comparable<T>> {…}