1 Generics, Type Safety, and Dynamic Data Structures.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
Java Generics.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
CS180 Generics and Type Safety Dynamic Data Structures 3/21/08.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 CS 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.
30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Stacks, Queues, and Deques
Chapter 19 Java Data Structures
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Java Generics.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Week 2 - Monday.  What did we talk about last time?  Exceptions  Threads  OOP  Interfaces.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
CS 2430 Day 26. Announcements Exam #2: Wednesday, April 3 –Review in lab on Tuesday, April 2 –Sample problems sent via .
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Chapter 18 Java Collections Framework
Computer Science 209 Software Development Java Collections.
Data structures Abstract data types Java classes for Data structures and ADTs.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
Self-Referential Classes A Self-referential class is a class that contains a reference to an object that has the same class type. –A self-referential class.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
CMSC 330: Organization of Programming Languages Java Generics.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Java Generics – Wildcards By: Anupam Chanda. 2 Generics and Subtyping We start to run into some new issues when we do some things that seem “normal”.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Object Oriented Programming in Java Habib Rostami Lecture 7.
CS-2851 Dr. Mark L. Hornick 1 Stacks and Queues Behavior vs. Structure.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 19 Java Data Structures
Software Development Java Collections
Building Java Programs
Comp 212: Intermediate Programming Lecture 18 – Java Generics
Winter 2019 CMPE212 5/3/2019 CMPE212 – Reminders
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Presentation transcript:

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 Today’s 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 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 Java Generics: Key Idea Parameterize type definitions –Parameterized classes and methods Provide type safety –Compiler performs type checking –Prevent runtime cast errors

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 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 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 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 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 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 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 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 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 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 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 Stack { void push( A a ) {... } A pop() {... }... } String s = "Hello"; Stack st = new Stack (); st.push( s );... s = st.pop();

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 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 Quiz Given the following class signature, what type of objects can the parameterized type T support? public class Quiz > {…}