Class 32: The Java Collections Framework



Similar documents
Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Data Structures in the Java API

Working with Java Collections

JAVA COLLECTIONS FRAMEWORK

The Java Collections Framework

Data Structures and Algorithms

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Per imparare a programmare bisogna programmare

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

CMSC 202H. ArrayList, Multidimensional Arrays

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Practical Session 4 Java Collections

Chapter 8: Bags and Sets

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Lecture 2: Data Structures Steven Skiena. skiena

D06 PROGRAMMING with JAVA

Basic Programming and PC Skills: Basic Programming and PC Skills:

Java SE 8 Programming

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Data Structures and Algorithms Lists

Software Development with UML and Java 2 SDJ I2, Spring 2010

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

CompSci-61B, Data Structures Final Exam

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Analysis of a Search Algorithm

Lecture 7: Class design for security

Java Interview Questions and Answers

Introduction to Object-Oriented Programming

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

1 of 1 24/05/ :23 AM

Java Map and Set collections

Java Software Structures

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Android Application Development Course Program

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Java EE Web Development Course Program

Structural Design Patterns Used in Data Structures Implementation

Java Coding Practices for Improved Application Performance

Introduction to Stacks

Big O and Limits Abstract Data Types Data Structure Grand Tour.

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

core 2 Basic Java Syntax

C++ INTERVIEW QUESTIONS

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Introduction to Programming System Design. CSCI 455x (4 Units)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Approach of Unit testing with the help of JUnit

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

LINKED DATA STRUCTURES

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Computing Concepts with Java Essentials

dictionary find definition word definition book index find relevant pages term list of page numbers

Symbol Tables. Introduction

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Efficient Data Structures for Decision Diagrams

Data Structures Fibonacci Heaps, Amortized Analysis

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

cs2010: algorithms and data structures

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

DATA STRUCTURES USING C

10CS35: Data Structures Using C

BCS2B02: OOP Concepts and Data Structures Using C++

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Project 4 DB A Simple database program

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

Ordered Lists and Binary Trees

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

C++ Programming Language

Lecture Notes on Binary Search Trees

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Java Training - A Brief Summary of Objects

Semantic Analysis: Types and Type Checking

Chapter 13: Query Processing. Basic Steps in Query Processing

The ADT Binary Search Tree

Lecture 12 Doubly Linked Lists (with Recursion)

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

Java the UML Way: Integrating Object-Oriented Design and Programming

Introduction: Abstract Data Types and Java Review

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java Programming Language

Computer. Course Description

CS 111 Classes I 1. Software Organization View to this point:

Génie Logiciel et Gestion de Projets. Refactoring

Loops and ArrayLists

Transcription:

Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come with the JDK; To talk about how you design a library of related classes To review which data structures are the best tools for a variety of algorithmic tasks 2 1

History In the original version of the Java Development Kit, JDK 1.0, developers were provided very few data structures. These were: Vector Stack: which extended Vector Hashtable: very similar to our implementation of HashMap Dictionary: an abstract class that defined the interface and some functionality for classes that map keys to values. Dictionary served as the base class for Hashtable. Enumeration: was a simple version of our Iterator that allowed you to iterate over instances of Hashtable and Vector. 3 The Java Collections Framework The Java designers realized that this set of data structures was inadequate. They prototyped a new set of data structures as a separate toolkit late in JDK 1.1, and then made it a formal part of the JDK in version 1.2. This later, fuller, better designed set of classes is called the Java Collections Framework. There is a good tutorial on its use at http://java.sun.com/docs/books/tutorial/collection s/index.html. 4 2

Collections Interfaces, 1 Collection Map Set List SortedMap SortedSet Iterator 5 ListIterator Collections Interfaces, 2 Collection: is the most basic interface; it has the functionality of an unordered list, aka a multiset, a set that doesn t not check for duplicates. Set: adds set semantics; that is, it won't allow duplicate members. List: adds list semantics; that is, a sense of order and position SortedSet: adds order to set semantics; our binary search tree that just consisted of keys without values could be implemented as a SortedSet 6 3

Collections Interfaces, 3 Map: the basic interface for data structures that map keys to values; it uses an inner class called an Entry SortedMap: a map of ordered keys with values; our binary search tree is a good example Iterator: our Iterator except that it is fail fast; it throws a ConcurrentModificationException if you use an instance after the underlying Collection has been modified. ListIterator: a bidirectional iterator. 7 Collection Implementations The Java designers worked out the architecture of interfaces independently of any data structures. In a second stage they created a number of concrete implementations of the interfaces based on slightly more sophisticated versions of the data structures that we have been studying: Resizable Array: similar to the technique used for our Stack implementation. Linked List: uses a doubly, not singly, linked list. Hash Table: very similar to our implementation except that it will grow the number of slots once the load factor passes a value that can be set in the constructor. Balanced Tree: similar to our binary search tree implementation but based on the more sophisticated Red- Black tree that rebalances the tree after some operations. 8 4

Collection Implementations, 2 Implementations Hash Table Resizable Array Balanced Tree Linked List List Array- List Linked- List Set HashSet Interfaces SortedSet Set TreeSet Map HashMap 9 Sorted Map TreeMap Collection Implementations, 3 Notice the gaps. There is no list based on a hash table. Why? What about a set implementation based on a linked list? The goal of the Java designers was to create a small set of implementations to get users started, not an exhaustive set. They expect that developers will extend the set of collection classes just as they expect that developers will add more stream classes. The most important part of the collection design was the architecture of interfaces. That's why they called it a framework. 10 5

Implementation Choices Be careful of implementation choices. Not all the implementations are going to be efficient at all their operations. For instance, an ArrayList will allow you to remove its first element by calling remove( 0 ). We already know this will be particularly inefficient. You can also iterate over a LinkedList, l, using the following code, but once again it will be very inefficient. Why? for ( int i = 0; i < l.size(); i++ ) { Object o = l.get( i ); // do what you need with o 11 Collection Interface public interface Collection { // Query Operations int size(); boolean isempty(); boolean contains(object o); boolean containsall(collection c); Iterator iterator(); Object[] toarray(); Object[] toarray(object a[]); boolean equals(object o); int hashcode(); 12 6

Collection Interface, 2 // Modification Operations boolean add(object o); boolean remove(object o); boolean addall(collection c); boolean removeall(collection c); boolean retainall(collection c); void clear(); 13 Bulk Operations Note the bulk operations. All the interfaces derived from Collection support them: boolean containsall( Collection c ) boolean addall( Collection c ) boolean removeall( Collection c ) boolean retainall( Collection c ) containsall() returns true if the target of the method contains all the elements in the argument collection. The other three methods return true if the operation changes the target collection. 14 7

Bulk Constructors All Collection (Map) implementations support at least two constructors. a default constructor that creates an empty Collection (Map) of the appropriate type, and a constructor that takes a Collection (Map) argument that creates a Collection (Map) of the appropriate type that contains references to all the objects in the Collection (Map) supplied as the argument. 15 Array Operations All Collection implementations also possess a method with the signature: Object [] toarray() which returns the contents of the collection in an appropriately sized array. A variant Object[] toarray(object a[]); returns all the elements of the collection that match the type of the array, a[], in a[] itself or an appropriately sized array of the same type. 16 8

Array Examples Collection c = new HashSet(); // put things in c String[] s = (String[]) c.toarray(new String[0]); returns all the String elements of c in an array of Strings. Collection c = new HashSet(); // if c contains only Strings String[] s = (String[]) c.toarray( ); 17 List Interface public interface List extends Collection { // adds the following to Collection boolean addall(int index, Collection c); Object get(int index); Object set(int index, Object element); void add(int index, Object element); Object remove(int index); int indexof(object o); int lastindexof(object o); ListIterator listiterator(); ListIterator listiterator(int index); List sublist(int fromindex, int toindex); 18 9

Views Several of the interfaces also support view operations. In a view operation, a collection returns another collection that provides a specialized and usually partial view of its contents. A good example is List sublist( int from, int to ) This method returns a second list that starts with the from'th element of the parent list and ends just before the to'th element. But the returned sublist is not a copy. It remains part of the original list. As an example, an elegant way to delete the 4th through 10th elements of a list is the following: mylist.sublist( 3, 10 ).clear(); 19 Set Interface public interface Set extends Collection { // has the same methods as Collection // but with stricter semantics 20 10

SortedSet Interface public interface SortedSet extends Set { // adds the following to Set Comparator comparator(); SortedSet subset(object fromelement, Object toelement); SortedSet headset(object toelement); SortedSet tailset(object fromelement); Object first(); Object last(); 21 Iterator Interface public interface Iterator { boolean hasnext(); Object next(); void remove(); 22 11

ListIterator Interface public interface ListIterator extends Iterator { // adds the following to Iterator boolean hasprevious(); Object previous(); int nextindex(); int previousindex(); void set(object o); void add(object o); 23 Concurrent Modification Iterators have to keep references to the underlying data structure to maintain their sense of current position. Thought experiment: create a LinkedList, add elements, get an iterator, advance it now using a method in the list not the iterator, delete the iterator's next item now call next() on the iterator what goes wrong? Any time you create an iterator, modify the underlying collection, and then use the iterator, you will get a ConcurrentModificationException. How do you think they implement the check? 24 12

Concurrent Modification, Before List Iterator first last current next Link Link Link Link null Item Item Item Item 25 Concurrent Modification, After List Iterator first last current next Link Link? Link null Item Item Item 26 13

Map Interface public interface Map { // Query Operations int size(); boolean isempty(); boolean containskey(object key); boolean containsvalue(object value); Object get(object key); 27 Map Interface, 2 // Modification Operations Object put(object key, Object value); Object remove(object key); void putall(map t); void clear(); // Views public Set keyset(); public Collection values(); public Set entryset(); boolean equals(object o); int hashcode(); 28 14

Nested Map.Entry Interface public interface Entry { Object getkey(); Object getvalue(); Object setvalue(object value); boolean equals(object o); int hashcode(); 29 Map Views Maps also provide views. In fact they are crucial because a Map does not provide an iterator() method. They are two separate idioms for iterating over a Map, depending on whether you want to iterate over the keys or the values: Map m =...; // iterates over keys for (Iterator i=m.keyset().iterator(); i.hasnext();) {... // iterates over values for (Iterator i=m.values().iterator(); i.hasnext();) {... In the second example, values() returns a Collection, not a Set, because the same value can occur multiple times in a map while a key must be unique. 30 15

SortedMap Interface public interface SortedMap extends Map { // adds the following to Map Comparator comparator(); SortedMap submap(object fromkey, Object tokey); SortedMap headmap(object tokey); SortedMap tailmap(object fromkey); Object firstkey(); Object lastkey(); 31 Optional Operations Not all implementations implement all the operations in an interface. The documentation makes it clear whether a particular implementation implements a given method. If it doesn't, it throws an UnsupportedOperationException (unchecked). At first, this just seems perverse, but the goal is to provide more flexibility. Imagine a program where you want to maintain a master index in which you want a normal user to be able to look up entries but only a privileged user to add entries to the index. The index could be implemented as a SortedMap, but then how could you keep an arbitrary user from adding and deleting entries? The answer is to subclass SortedMap and override each method you wanted to forbid with a simple method that throws an UnsupportedOperationException. 32 16

Algorithms The Collections class contains implementations of a number of useful algorithms implemented as static methods that take a List or sometimes a more general Collection as the target of the algorithm. Algorithms include sort(), reverse(), min(), max(), fill(object o), etc. static void sort( List l, Comparator c ) static void fill( List l, Object o ) There is a similar class Arrays, which implements most of the same algorithms for arrays. 33 Read-Only Collections Collections can also produce unmodifiable (read only) views of all types of collections that will throw an UnsupportedOperationException on any write operation: public static Collection unmodifiablecollection(collection c); public static Set unmodifiableset(set s);... 34 17