CS180 Generics and Type Safety Dynamic Data Structures 3/21/08.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
ITEC200 Week04 Lists and the Collection Interface.
Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
Java Review Interface, Casting, Generics, Iterator.
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
1 Generics, Type Safety, and Dynamic Data Structures.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
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.
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
Chapter 19 Java Data Structures
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
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.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Effective Java: Generics Last Updated: Spring 2009.
Data structures and algorithms in the collection framework 1 Part 2.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CS 46B: Introduction to Data Structures July 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 18 Java Collections Framework
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Data structures Abstract data types Java classes for Data structures and ADTs.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Collections –data structures and Algorithms L. Grewe.
Data structures and algorithms in the collection framework 1.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Today’s Agenda  Generic  Iterators CS2336: Computer Science II.
CS102 – Data Structures Lists, Stacks, Queues, Trees & HashTables. David Davenport.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
13 Collections Framework. 2 Contents What is Collection? Collections Framework Collections Hierarchy Collections Implementations Set List Map.
List Interface and Linked List Mrs. Furman March 25, 2010.
Nov 22, 2010IAT 2651 Java Collections. Nov 22, 2010IAT 2652 Data Structures  With a collection of data, we often want to do many things –Organize –Iterate.
Maps Nick Mouriski.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Linked Lists CS 367 – Introduction to Data Structures.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
UNIT-II Topics to be covered Singly linked list Circular linked list
Advanced Programming 7/10/20161 Ananda Gunawardena.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Java Collections CHAPTER 3-February-2003
Linked Data Structures
Chapter 19 Java Data Structures
Comp 212: Intermediate Programming Lecture 18 – Java Generics
Presentation transcript:

CS180 Generics and Type Safety Dynamic Data Structures 3/21/08

Administriva Projects –Hand back project 5 gradesheets –Project 6 is due next Wednesday 3/26 –2 more projects for the semester Project 7 – recursion –Fairly comprehensive of the past month’s topics Project 8 – GUIs

Generics Goals –Simple way to provide flexibility of types for a single class –Move traditional runtime errors to compile time – safer! Suppose you want to make a simple generic box class class Box { private Object data; public Box(Object data) { this.data = data; } public Object getData() { return data; }

Generics – Type Safety Problem: While our box can contain any object, it is not type safe! class Box { private Object data; public Box(Object data) { this.data = data; } public Object getData() { return data; } Box box1 = new Box(“String box”); Box box2 = new Box(42); // valid but have to downcast (unsafe?) String str = (String)box1.getData(); int x = (Integer)box2.getData(); // valid but not good (illogical) box1 = box2; // compiles, but ClassCastException (oh no!) String str = (String)box2.getData();

Solution Trivial solution: make a box class for all the types of boxes you need –What if you need an incredible number of boxes? Annoying! Java’s solution: introduce a parameterized type to make the class generic –Basic idea: swap type Object with a more clearly identifiable type –Moves runtime problems to compile time, which is good class Box { private T data; public Box(T data) { this.data = data; } public T getData() { return data; } Box box1 = new Box(“String box”); Box box2 = new Box(42); // valid and no more casts! String str = box1.getData(); int x = box2.getData(); // compile time error, yay! box1 = box2; // compile time error, yay! String str = box2.getData();

Parameterized Classes Syntax Generic class with type class Box {…} Can have many types class MultiBox {…} Can extend a parameterized class class IntBox extends Box {…} class SpecialBox extends Box {…}

Bounded Parameterized Types (Optional) You can also restrict the type you want –Allows additional methods which the parameterized type can use class ComparableBox > { private E data; public ComparableBox(E data) { this.data = data; } public E getData() { return data; } public int compareTo(E box) { return data.compareTo(box.getData()); }

Parameterized Methods (Optional) 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() 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

Dynamic Data Structures The problem with arrays: they are static –If more space needed, must create new array and move everything over –Cumbersome! Dynamic Data Structures –Solves this problem –Flexible in size with different strategies –Different organizational techniques create different useful structures

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 –Vector –LinkedList –Stack FILO –TreeMap A Map Sorted –HashTable –HashMap … They all use generics!

Java Collections Common functionality –add –clear –contains –equals –isEmpty –size –remove Specific classes have more functions

Vectors Basically a resizable array When more space is needed, larger array is allocated (typically by more than 1 so that re-allocation is not done excessively) –By some constant amount –Doubling –User can control allocation time Vector vector = new Vector (); vector.add(“vectors”); vector.add(“are”); vector.add(“resizable”); vector.add(“arrays”); if (vector.elementAt(3).equals(“arrays”)) System.out.println(“success!”); vector.remove(“resizable”); if (vector.elementAt(2).equals(“arrays”)) System.out.println(“success!”); vector.replace(“structures”, 2);

Collections and Generics Before generics, collections were not necessarily homogeneous –Reason for warnings in project 5 –Type unsafe data structures Now, type requirements make homogeneous structures –Type safe data structures // what does this vector hold?!? Vector vector = new Vector(); vector.add(“a string”); vector.add(43); vector.add(new Vector()); // ah, this vector holds integers! Vector vector = new Vector (); vector.add(32); vector.add(12); vector.add(-4); int x = vector.elementAt(2);

LinkedList A chain of nodes, accessible one at a time When to use Vector, when to use LinkedList? –Vectors Adjacent memory allocated like an array – very good for accessing things in order Fast indexing for elements Poor at resizing –LinkedList Memory locations “jump” from pointer to pointer Indexing can be linear (traverse down the list) Excellent at resizing – don’t have to re-allocate memory, just new memory ArrayList – another alternative LinkedList list = new LinkedList (); list.add(“lists”); list.add(“are”); list.add(“chained”); list.add(“nodes”); if (list.elementAt(3).equals(“ nodes”)) System.out.println(“success!”); list.remove(“chained”); if (list.elementAt(2).equals(“nodes”)) System.out.println(“success!”);

Generic Linked List public class MyLinkedList { private Node head; // inner class node – outside world does not need to know implementation details private class Node { private T data;// parameterized type is scoped in! private Node next;// also known as link public Node(T data, Node next) { this.data = data; this.next = next; } … } public MyLinkedList() { head = null; } … }

Pointer Exercise Inserting a node (value 3) into a list 241 head 1) Move pointers into place prevcurr 3 add 241 head 2) Change prev’s next pointer prevcurr 3 add 241 head 3) Change add’s next pointer prevcurr 3 add

Pointer Exercise Deleting a node from a list (node 3) 2341 head 1) Move pointers into place prevcurr 2341 head 2) Move prev’s next pointer to curr’s next pointer prevcurr 2341 head 3) Cut off curr node and delete it (done for you by Java) prevcurr

Hash Tables and Maps Create correspondence between key and value (or bucket) pairs –Use key to look up value in table or map –To store multiple items (single key to multiple values), use a collection as the value! HashMap phonebook = new HashMap (); String name = “Smith, Joe”; String number = “ ”; phonebook.put(name, number); String fetched = phonebook.get(name); if (fetched.equals(number)) System.out.println(“success!”); HashMap > phonebook = new HashMap >(); String name = “Smith, Joe”; String number = “ ”; char letter = name.charAt(0); LinkedList entries; if (phonebook.containsKey(letter)) entries = phonebook.get(letter); else entries = new LinkedList (); entries.add(new PhoneEntry(name, number)); phonebook.put(letter, entries);

Iteration Collections can return an iterator to go through each object in the collection –Use next, hasNext methods to iterate In Java 5.0, can use for-each loop to do the same thing –Can even apply to arrays! LinkedList list = new LinkedList (); addStuffToList(list); for (int k=0; k<list.size(); k++) System.out.println(list.elementAt(k)); LinkedList list = new LinkedList (); addStuffToList(list); Iterator iterator = list.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); LinkedList list = new LinkedList (); addStuffToList(list); for (String s : list) System.out.println(s);

Quiz What is the purpose of defining the node class of a linked list as an inner class? What is the purpose of generics and parameterized types in Java? In what situation should an array be used over a vector?