Computer Science II (Spring )

Similar documents
CONTAİNERS COLLECTİONS

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Class 32: The Java Collections Framework

Generics Collection Framework

EECS 2011 M: Fundamentals of Data Structures

The Java Collections Framework and Lists in Java Parts 1 & 2

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Java Collections Framework

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

Topic 10: The Java Collections Framework (and Iterators)

Generic classes & the Java Collections Framework. *Really* Reusable Code

Collections, Maps and Generics

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Collections (Java) Collections Framework

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

What is the Java Collections Framework?

5/23/2015. Core Java Syllabus. VikRam ShaRma

Computer Science II (20073) Week 1: Review and Inheritance

Hash tables. hashing -- idea collision resolution. hash function Java hashcode() for HashMap and HashSet big-o time bounds applications

Software 1 with Java. Recitation No. 6 (Collections)

EXAMINATIONS 2016 TRIMESTER 2

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

Algorithms. Produced by. Eamonn de Leastar

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

Collections Questions

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Data Structures. COMS W1007 Introduction to Computer Science. Christopher Conway 1 July 2003

Computer Science II (20082) Week 1: Review and Inheritance

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

Java Collections Framework reloaded

Building Java Programs

CS Ananda Gunawardena

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Lecture 6 Collections

The Java Collections Framework. Chapters 7.5

COMP6700/2140 Abstract Data Types: Queue, Set, Map

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

CS11 Java. Winter Lecture 8

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

CISC 3115 TY3. C28a: Set. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 11/29/2018 CUNY Brooklyn College

AP Computer Science 4325

תוכנה 1 מבני נתונים גנריים

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Lecture 4. The Java Collections Framework

PIC 20A Collections and Data Structures

An Interface with Generics

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

Object-Oriented Programming with Java

JAVA SYLLABUS FOR 6 WEEKS

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

9/16/2010 CS Ananda Gunawardena

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collection Framework

Java Magistère BFA

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Fundamental language mechanisms

CS2113 Lab: Collections 10/29/2018

EXAMINATIONS 2017 TRIMESTER 2

Pieter van den Hombergh Richard van den Ham. February 8, 2018

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

CS 307 Final Spring 2008

CS2110: Software Development Methods. Maps and Sets in Java

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Java Collections Framework: Interfaces

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Introduction to Computer Science I

Interfaces and Collections

Introduction to Collections

MIT AITI Lecture 18 Collections - Part 1

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS2013 Course Syllabus Spring 2017 Lecture: Friday 8:00 A.M. 9:40 A.M. Lab: Friday 9:40 A.M. 12:00 Noon

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CS61B Lecture #17. Last modified: Mon Oct 1 13:40: CS61B: Lecture #17 1

Sets and Maps. Part of the Collections Framework

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Introduction to Programming Using Java (98-388)

Model Solutions. COMP 103: Test May, 2013

Collections. The Java Collections Framework. The Interfaces

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

Transcription:

Computer Science II 4003-232-01 (Spring 2007-2008) Week 5: Generics, Java Collection Framework Richard Zanibbi Rochester Institute of Technology

Generic Types in Java (Ch. 21 in Liang)

What are Generic Types or Generics? Definition Reference type parameters for used to modify class, interface and method definitions (at compile time) Recall: normal (actual) method parameters: values from a primitive/reference type (at run-time for variables) Generic types define macros: the class name replaces the type parameter in the source code ( search and replace ) Syntax <C> for parameter, use as C elsewhere (C must be a class/interface) public class Widget <C> {... } // class definition Widget<String> widget = new Widget<String>(); // instantiation public <C> void test( C o1, int x ) { C temp;... } // method definition widget.<integer>test(new Integer(5), 1); // invoking method Purpose: Avoiding Dangerous Polymorphism Prevent run-time errors (exceptions) due to type errors (casts) - 3 -

Example: Comparable Interface Prior to JDK 1.5 (and Generic Types): public interface Comparable { public int compareto(object o) } Comparable c = new Date(); System.out.println(c.compareTo( red )); run-time error JDK 1.5 (Generic Types): public Interface Comparable<T> { public int compareto(t o) } Comparable<Date> c = new Date(); System.out.println(c.compareTo( red )); compile-time error - 4 -

Raw Types and Associated Compiler Warnings Raw Types (for backward compatability) Classes with generic type parameters used without the type parameters defined e.g. Comparator c ~= Comparator<Object> c Recommendation: always set generic type parameters for variable types e.g. Comparator<Date> c = new Date(); Compiler Warnings javac will give a warning about possibly unsafe operations (type errors) at run-time for raw types use -Xlint:unchecked flag (or, -Xlint:all) for detailed messages. javac will not compile programs whose generic types cannot be properly defined e.g. Max.java, Max1.java (pp. 699-700 in Liang) - 5 -

Overview: Data Structures and Abstract Data Types

Storing Data in Java Variables Primitive type (int, double, boolean, etc.) Variable name refers to a memory location containing a primitive value Reference type (Object, String, Integer, MyClass, etc.) Variable name refers to a memory location containing a reference value for data belonging to an object Data Structure A formal organization of a set of data (e.g. variables) e.g. Arrays: variables of a given type in an integer-indexed sequence int intarray[ ] = {1, 2}; int a = intarray[0]; intarray[1] = 5; e.g. Objects: data member names used to index variables player.name, player.hits, player.team... player.hits = 100; - 7 -

Abstract Data Types (ADTs) Purpose Define interfaces for complex data structures Hide (abstract) implementation details of operations that query and update Define operations to be independent of the element type (Java: generic ) Some Common ADTs List: Sequence of elements. Elements may be inserted or removed from any position in the list Stack: List with last-in, first-out (LIFO) behaviour ( most recent ) e.g. call stack Queue: List with first-in, first-out (FIFO) ( in-order ) e.g. lining up at a fast-food restaurant or bank - 8 -

Common ADTs, Cont d Tree: Graph with directed edges, each node has one parent (except root), no cycles. A decision tree representing possible moves in a game of tic-tac-toe. Set: Unordered group of unique items Students in a class, the set of words in a text file Map: Set of entries, each with unique key and (possibly non-unique) value Student grade sheet: (StudentId, Grade) Frequency of words in a text file (Word, Count) - 9 -

Set s s.add(e) (Binary Search) Tree t < C > B D A C s.add(e) B D A C E t.add(f) A B D E ABCD l.add(e) List l ABCDE l.add(e,2) ABECDE A B C D E F Map m (2, Maria) (1, Joe) m.add((3,dina)) (2, Maria) (1, Joe) (3, Dina) m.add((1,john)) m.add(2,maria) (2, Maria) (1, John) (3, Dina) - 10 -

Example: Implementing Abstract Data Types List ADT Represents series of elements, insertion and deletion of elements Some Possible Implementations: Arrays: L.add(E) would copy E at the end of the array, L.get(4) returns 5 th item in array Linked List: (objects forming a chain of references) L.add(E) would create a link from last node to a new node for E ; l.get(4) traverses the graph and then returns the 5 th item Choosing an Implementation for an ADT Depending on common operations, some better than others Retrieving elements in list faster for array implementation Inserting, deleting elements faster for linked list implementation in general case - 11 -

Ordering in Unordered Sets and Maps Unordered in Theory vs. in Code In practice, an ordering of elements is used to implement a set, as memory and files store data as lists of bytes. Sets By definition, a set is an unordered group of unique elements Maps By definition, a map is a set of (key,value) pairs, where all keys are unique. Ordering Sets and Maps We can order the storage of set elements by: 1. The order in which elements are added (e.g. in a list) 2. The values of keys or data elements themselves (e.g. using a binary search tree) 3. A value computed for each element ( hash code ) that determines where an element is stored (e.g. in a hash table, a sophisticated ADT built on arrays); for maps, hash code computed using key value - 12 -

Exercise: Generics and ADTs Part A 1. In one sentence, what is a generic type? 2. What errors are generic types designed to prevent? 3. Which javac flag will show details for (type) unsafe operations? 4. What do the following represent: a) <? extends MyClass> b) <? super YourClass> c) <E extends Comparator<E>> 5. Write a java class GenX which has a generic type parameter T, a public data member identity of type T, and a constructor that takes an initial value for identity. Add a main method that constructs one GenX object using type String, and another using type Integer. - 13 -

Part B 1. What is an abstract data type? 2. How is a list different from a set? 3. How are elements stored in a binary search tree (BST)? 4. In what ways can we order the elements of a set, or pairs of a map? 5. Are sets and map elements/pairs ordered in their ADT definitions? - 14 -

ADTs in Java: The Java Collections Framework

The Java Collections Framework Definition Set of interfaces, abstract and concrete classes that define common abstract data types in Java e.g. list, stack, queue, set, map Part of the java.util package Implementation Extensive use of generic types, hash codes (Object.hashCode()), and Comparable interface (compareto(), e.g. for sorting) Collection Interface Defines common operations for sets and lists ( unordered ops.) Maps Represented by separate interfaces from list/set (due to key/value relationship vs. a group of elements) - 16 -

Java Collections Interfaces (slide: Carl Reynolds) Note: Some of the material on these slides was taken from the Java Tutorial at http://www.java.sun.com/docs/books/tutorial - 17 -

- 18 -

Implementation Classes (slide derived from: Carl Reynolds) Interface Implementation Historical Set HashSet TreeSet LinkedHashSet List ArrayList LinkedList Vector Stack Map HashMap TreeMap LinkedHashMap HashTable Properties Note: When writing programs use the interfaces rather than the implementation classes where you can: this makes it easier to change implementations of an ADT. - 19 -

Notes on Unordered Collections (Set, Map Implementations) HashMap, HashSet Hash table implementation of set/map Use hash codes (integer values) to determine where set elements or (key,value) pairs are stored in the hash table (array) LinkedHashMap, LinkedHashSet Provide support for arranging set elements or (key,value) pairs by order of insertion by adding a linked list within the hash table elements TreeMap,TreeSet Use binary search tree implementations to order set elements by value, or (key,value) pairs by key value - 20 -

Sets in the Collections Framework E: a generic type parameter - 21 -

E: a generic type parameter - 22 -

HashSet (Example: TestHashSet.java, p. 717) Methods: Except for constructors, defined methods identical to Collection Element Storage: Unordered, but stored in a hash table according to their hash codes **All elements are unique Do not expect to see elements in the order you add them when you output them using tostring(). Hash Codes Most classes in Java API override the hashcode() method in the Object class Need to be defined to properly disperse set elements in storage (i.e. throughout locations of the hash table) For two equivalent objects, hash codes must be the same - 23 -

LinkedHashSet (example: TestLinkedHashSet.java, p. 718) Methods Again, same as Collection Interface except for constructors Addition to HashSet Elements in hash table contain an extra field defining order in which elements are added (as a linked list) List maintained by the class Hash Codes Notes from previous slide still apply (e.g. equivalent objects, equivalent hash codes) - 24 -

Ordered Sets: TreeSet (example: TestTreeSet.java) Methods Add methods from SortedSet interface: first(), last(), headset(toelement: E), tailset(fromelement: E) Implementation A binary search tree, such that either: 1. Objects (elements) implement the Comparable interface (compareto() ) ( natural order of objects in a class), or 2. TreeSet is constructed using an object implementing the Comparator interface (compare()) to determine the ordering (permits comparing objects of the same or different classes, create different orderings) One of these will determine the ordering of elements. Notes It is faster to use a hash set to retrieve elements, as TreeSet keeps elements in a sorted order Can construct a tree set using an existing collection (e.g. a hash set) - 25 -

Iterator Interface Purpose Provides uniform way to traverse sets and lists Instance of Iterator given by iterator() method in Collection Operations Similar behaviour to operations used in Scanner to obtain a sequence of tokens Check if all elements have been visited (hasnext()) Get next element in order imposed by the iterator (next()) remove() the last element returned by next() - 26 -

List Interface (modified slide from Carl Reynolds) // Positional Access get(int):e; set(int,e):e; add(int, E):void; remove(int index):e; addall(int, Collection):boolean; // Search int indexof(e); int lastindexof(e); List<E> // Iteration listiterator():listiterator<e>; listiterator(int):listiterator<e>; // Range-view List sublist(int, int):list<e>; - 27 -

ListIterator (modified slide from Carl Reynolds) the ListIterator interface extends Iterator Forward and reverse directions are possible ListIterator is available for Java Lists, such as the LinkedList implementation ListIterator <E> hasnext():boolean; next():e; hasprevious():boolean; previous(): E; nextindex(): int; previousindex(): int; remove():void; set(e o): void; add(e o): void; - 28 -

The Collections Class Operations for Manipulating Collections Includes static operations for sorting, searching, replacing elements, finding max/min element, and to copy and alter collections in various ways. (using this in lab5) Note! Collection is an interface for an abstract data type, Collections is a separate class for methods operating on collections. - 29 -

List: Example TestArrayAndLinkedList.java (course web page) - 30 -

Map <K,V> Interface (modified slide from Carl Reynolds) Map <K,V> Entry <K,V> - 31 -

Map Examples CountOccurranceOfWords.java (course web page) TestMap.java (from text) - 32 -

Comparator Interface (a generic class similar to Comparable) (comparator slides adapted from Carl Reynolds) You may define an alternate ordering for objects of a class using objects implementing the Comparator Interface (i.e. rather than using compareto()) Sort people by age instead of name Sort cars by year instead of Make and Model Sort clients by city instead of name Sort words alphabetically regardless of case - 33 -

Comparator<T> Interface One method: compare( T o1, T o2 ) Returns: negative if o1 < o2 Zero if o1 == o2 positive if o1 > o2-34 -

Example Comparator: Compare 2 Strings regardless of case import java.util.*; public class CaseInsensitiveComparator implements Comparator<String> { public int compare( String stringone, String stringtwo ) { } } // Shift both strings to lower case, and then use the // usual String instance method compareto() return stringone.tolowercase().compareto( stringtwo.tolowercase() ); - 35 -