The Collections API 9/5/00 1. Lecture Objectives

Similar documents
Data Structures in the Java API

JAVA COLLECTIONS FRAMEWORK

Class 32: The Java Collections Framework

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

Datastrukturer och standardalgoritmer i Java

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

The Java Collections Framework

D06 PROGRAMMING with JAVA

Software Engineering II. Java 2 Collections. Bartosz Walter <Bartek.Walter@man.poznan.pl>

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

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

Java Map and Set collections

Using Files as Input/Output in Java 5.0 Applications

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

Universidad Carlos III de Madrid

Java Coding Practices for Improved Application Performance

1 of 1 24/05/ :23 AM

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

The Interface Concept

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

Working with Java Collections

Data Structures and Algorithms

public static void main(string[] args) { System.out.println("hello, world"); } }

Java SE 8 Programming

Contents. 9-1 Copyright (c) N. Afshartous

core 2 Basic Java Syntax

Lecture J - Exceptions

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

Practical Session 4 Java Collections

Data Structures and Algorithms Lists

Computer. Course Description

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

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:

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

Lecture 7: Class design for security

CMSC 202H. ArrayList, Multidimensional Arrays

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

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Java Application Developer Certificate Program Competencies

Introduction to Data Structures

CS506 Web Design and Development Solved Online Quiz No. 01

C++ INTERVIEW QUESTIONS

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

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

LINKED DATA STRUCTURES

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Fundamentals of Java Programming

Lecture 2: Data Structures Steven Skiena. skiena

Algorithms and Data Structures Written Exam Proposed SOLUTION

Visualising Java Data Structures as Graphs

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

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

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

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

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

Java Interview Questions and Answers

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

Chapter 3: Restricted Structures Page 1

Structural Design Patterns Used in Data Structures Implementation

Per imparare a programmare bisogna programmare

Software Engineering Techniques

Java from a C perspective. Plan

Hadoop + Clojure. Hadoop World NYC Friday, October 2, Stuart Sierra, AltLaw.org

16 Collection Classes

What are exceptions? Bad things happen occasionally

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)

Programming with Data Structures

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

Computer Programming I

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Estrutura com iterador-1

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Data Structures in Java. Session 15 Instructor: Bert Huang

: provid.ir

Iteration CHAPTER 6. Topic Summary

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

10CS35: Data Structures Using C

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Crash Course in Java

AP Computer Science Java Subset

Circular Linked List. Algorithms and Data Structures

Efficient Data Structures for Decision Diagrams

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

Programming Languages CIS 443

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

Explain the relationship between a class and an object. Which is general and which is specific?

Node-Based Structures Linked Lists: Implementation

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

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

Capabilities of a Java Test Execution Framework by Erick Griffin

Building a Multi-Threaded Web Server

cs2010: algorithms and data structures

Analysis of a Search Algorithm

Java Software Structures

Chapter 8: Bags and Sets

14/05/2013 Ed Merks EDL V1.0 1

JAVA INTERVIEW QUESTIONS

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Extreme Computing. Hadoop MapReduce in more detail.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Transcription:

The Collections API Mark Allen Weiss Copyright 2000 9/5/00 1 Lecture Objectives To see some bad design (Java 1.1) To see a better design (Java 1.2) To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 2

The Collections API in Java 1.1 Basically four classes plus one interface: Vector (resizeable generic array) Stack Hashtable (map of keys and values) Properties (map of keys and values that are Strings) Enumeration (a sloppy iterator pattern) Pathetic Design Stack IS-A Vector? Properties IS-A Hashtable? Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 3 The Collections API In Java 1.2 Deprecates the Java 1.1 stuff Contains new data structures including linked list, queue, set, and map. Contains generic algorithms including sorting. Mostly in java.util. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 4

Outline Provide an overview of the Collections API Discuss the basic supporting interfaces. Discuss the new basic data structures. Illustrate a sample program that generates a concordance (sorted listing of words with line numbers). Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 5 Overview of Collections API Much better than data structures in Java 1.1. Defines a new iteration mechanism (the Iterator); makes the Enumeration semideprecated. Inheritance-based (of course) Still incomplete. Though intended to be much smaller than STL, much is missing. Not thread-safe. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 6

Basic Supporting Interfaces There are some new supporting interfaces. The four most important are: Collection Iterator Comparable Comparator Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 7 Collection Interface Represents a group of objects (its elements) Different implementations place restrictions (such as allowing/disallowing duplicates, maintaining the collection in sorted order) Basic operations: boolean contains( Object element ) boolean isempty( ) int size( ) Iterator iterator( ) To design your own implementation of a Collection, extend AbstractCollection. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 8

More On Collection All collections, by convention, have two constructors: Construct empty Construct with a set of references that reference objects in any other collection AbstractCollection is an abstract class that implements many of the generic methods in the Collection interface. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 9 Iterator Interface Provides three methods that are used to access any Collection. boolean hasnext( ) Object next( ) void remove( ) hasnext returns true if the iteration has more items. next returns the next item and advances the iterator. remove removes the last accessed item (can t be called twice in a row). Officially preferred over Enumeration. Not a great iterator pattern because advancing and accessing current item are combined. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 10

Example Output the contents of any Collection. static void printcollection( Collection C ) Iterator itr = C.iterator( ); while( itr.hasnext( ) ) System.out.println( itr.next( ) ); If the underlying collection is sorted, the output will be sorted. Not bidirectional (but other iterators are). There are no public concrete iterators!! Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 11 How Do You Get An Iterator? Each Collection class defines a concrete class that implements the Iterator interface ArrayList could define ArrayListIterator TreeSet could define TreeSetIterator The iterator() method creates an instance of the appropriate concrete class and returns it. Static type of the return is Iterator. Dynamic type is the concrete Iterator. Could make the concrete implementation of Iterator package-visible and hide it. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 12

Comparable Interface Defined in java.lang. Has one method: int compareto( Object rhs ) throws ClassCastException Same semantics as String. String implements Comparable, as do the primitive wrapper classes (e.g. Integer). If you have a Comparable class in your code, you may have a conflict in Java 1.2. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 13 Comparator Interface Has one method: int compares( Object lhs, Object rhs ) Compares two objects, with return value that is like compareto. Use to override the default (or non-existent ordering) for collections that are sorted. Similar to the function object in STL. Predefined constant function object is Collections.REVERSE_ORDER. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 14

Example of Comparator Sorting strings by length. Need to provide a comparison object. final class Comp implements Comparator public int compare( Object lhs, Object rhs ) return ((String)lhs).length( ) - ((String)rhs).length( ); // In some other class static void sortlistofstringsbylength( List L ) Collections.sort( L, new Comp( ) ); Note: latest version uses stable mergesort. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 15 Why Java Needs Templates Although function object in previous example looks almost the same as C++ STL code, the comparison cannot be inlined. Result: sorting simple things is relatively expensive because each comparison has the overhead of a method call. Similar to problems with qsort in C. Lots of parameterized type proposals are under consideration for Java, but none seem to solve this problem. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 16

Data Structures Several data structures List, with list iterator Stack and Queue Set Map Not thread-safe. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 17 List Ordered collection (also known as sequence). Position in the list matters and can be specified by an integer index (0 is first position). Elements are not necessarily sorted. List is an interface. It is implemented by ArrayList, LinkedList (also Vector). Watch out for java.awt.list conflict. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 18

ArrayList and Vector Useful if you need to access by position, because you can do direct indexing. Insertions and deletions are expensive, except at high-end. Insertion at the end of an ArrayList causes an expansion if full with a guarantee of efficient performance. ArrayList is preferred over Vector. Vector is retrofitted to implement List interface. Useful if thread-safety is needed. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 19 LinkedList methods Implements a doubly-linked List. Lots of methods. Here are some: void addfirst( ) void addlast( ) Object getfirst( ) Object getlast( ) Object removefirst( ) Object removelast( ) void clear( ) ListIterator listiterator( int index ) Can implement stack and queue operations. Access with get and set supported but obviously horrendously slow. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 20

List (Continued) ListIterator is an interface that supports bi-directional iteration. Also (optionally) supports add (insert a new element prior to the next element in the iteration) and remove (removes last accessed element) Stack class from Java 1.1 is still here, but is synchronized and could be slow. There is no class named Queue. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 21 Using The List Interface Type If only ArrayList or LinkedList operations you are using are defined in List interface, should declare the reference using the List interface. Makes code more flexible Can change implementation from ArrayList to LinkedList later Same idea of preferring Reader/Writer as reference types Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 22

Optional Methods Starting in Java 1.2, interfaces can specify that some of its methods are optional. Implementor will throw UnsupportedOperationException if it does not want to implement an optional method. This is a runtime exception. Purely a convention; no language rule involved. Useful if you are lazy; or implementing immutable containers Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 23 More On Optional Methods Convention is that interface will document that the method might not be supported. Caller is expected to check documentation of class that implements the interface to see if method is supported. If caller doesn t do that, and calls the method anyway, will get an exception. Clearly this is considered a programming error, so it is a runtime exception. Optional methods are somewhat controversial. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 24

Sets Set is an interface that extends Collection. Duplicates are not allowed. Methods are: boolean add( Object element ) boolean remove( Object element ) HashSet is an efficient implementation. Uses hashcode. Recall that the hashcode of two objects must return the same value if the two objects are considered equal. Otherwise, object won t be found in a HashSet. TreeSet is a sorted-order (red-black tree version). Uses natural item order, or can be constructed with a Comparator. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 25 Maps Map is an interface that extends Collection and stores elements that consists of key, value pairs. Keys must be unique. Methods are: Object put( Object key, Object value ) Object get( Object key ) Object containskey( Object key ) Object remove( Object key ) HashMap and TreeMap implement Map. The latter keeps keys in sorted order. keys and values may be null. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 26

Getting a Collection from a Map A collection of keys, values, or key/value pairs can be extracted from the map. An iterator can then traverse the collection. Set keyset( ) Collection values( ) Set entryset( ) Each key/value entry is of the type Map.Entry. Use getkey and getvalue on the Map.Entry object. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 27 Concordance Example Read file containing words (several to a line). Output each unique word, and a list of line number on which it occurs. Basic algorithm: Use a TreeMap: map words to a linked list of lines. When the TreeMap is iterated, words come out in sorted order. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 28

Concordance Code Part I import java.util.*; import java.io.*; class Concordance public static void main( String [ ] args ) try BufferedReader infile = new BufferedReader( new FileReader( args[0] ) ); Map wordmap = new TreeMap( ); String oneline; // Read the words; add them to wordmap for(int linenum = 1; (oneline = infile.readline())!= null; linenum++) StringTokenizer st = new StringTokenizer( oneline ); Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 29 Concordance Code: Part II while( st.hasmoretokens( ) ) String word = st.nexttoken( ); List lines = (List) wordmap.get( word ); if( lines == null ) lines = new LinkedList( ); wordmap.put( word, lines ); lines.add( new Integer( linenum ) ); // Go through the word map Iterator itr = wordmap.entryset( ).iterator( ); while( itr.hasnext( ) ) printentry( (Map.Entry) itr.next( ) ); catch( IOException e ) e.printstacktrace( ); Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 30

Concordance Code: Part III public static void printentry( Map.Entry entry ) // Print the word System.out.println( entry.getkey( ) + ":" ); // Now print the line numbers Iterator itr = ((List)(entry.getValue())).iterator(); System.out.print( "\t" + itr.next( ) ); while( itr.hasnext( ) ) System.out.print( ", " + itr.next( ) ); System.out.println( ); Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 31 Summary Collections API has some power, but is still a work in progress. Needs: Priority Queue Efficient synchronized algorithms Even so, it s easy to use, and probably better than you could casually do yourself. Tuesday, September 05, 2000 Copyright 1996, 1999, M. A. Weiss 32