The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Similar documents
Notes on access restrictions

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

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

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

CONTAİNERS COLLECTİONS

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

Collections Questions

Lists. The List ADT. Reading: Textbook Sections

Collections. The Java Collections Framework. The Interfaces

Functors. 01/23/03 Lecture 5 1

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/22/04 Lecture 4 1

Lecture 6 Collections

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

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

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

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

The Java Collections Framework. Chapters 7.5

package weiss.util; // Fig , pg // Fig 6.16,6.17, pg package weiss.util;

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

Sets and Maps. Part of the Collections Framework

Java Collections Framework: Interfaces

Java Collections Framework reloaded

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

CS11 Java. Winter Lecture 8

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Class 32: The Java Collections Framework

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

CS Programming Language Java. Fall 2004 Sept. 29

Lecture 4. The Java Collections Framework

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/30/03 Lecture 7 1

CISC 3115 TY3. C24a: Lists. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 11/15/2018 CUNY Brooklyn College

182 review 1. Course Goals

CSC 1214: Object-Oriented Programming

Arrays organize each data element as sequential memory cells each accessed by an index. data data data data data data data data

Generics. IRS W-9 Form

Core Java Contents. Duration: 25 Hours (1 Month)

Generics Collection Framework

Chapter 10 Collections

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

Collections Framework: Part 2

PIC 20A Collections and Data Structures

Implementation. (Mapping to Java) Jörg Kienzle & Alfred Strohmeier. COMP-533 Implementation

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

MIT AITI Lecture 18 Collections - Part 1

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Class 26: Linked Lists

COP 3530, Course Outcomes

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Collection Framework Collection, Set, Queue, List, Map 3

COMP 103. Data Structures and Algorithms

Collections (Java) Collections Framework

CS 307 Final Spring 2008

CS2110: Software Development Methods. Maps and Sets in Java

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

USAL1J: Java Collections. S. Rosmorduc

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

Generics and collections

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Lists using LinkedList

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

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

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

A simple map: Hashtable

Topic 10: The Java Collections Framework (and Iterators)

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

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

Model Solutions. COMP 103: Test April, 2013

13 A: External Algorithms II; Disjoint Sets; Java API Support

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

Lecture 16: Case Study: The Java Collections API

JAVA. Duration: 2 Months

Fundamental language mechanisms

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

An Introduction to Data Structures

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

Java Collection Framework

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

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

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

CIS 265 Exam 2 First Name Last Name

Algorithms. Produced by. Eamonn de Leastar

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

An Interface with Generics

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

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

DM550 Introduction to Programming part 2. Jan Baumbach.

ITI Introduction to Computing II

School of Computing and Information Sciences. Course Title: Data Structures Date: 3/30/2010 Course Number: COP 3530 Number of Credits: 3

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

Generic Programming Recursive Binary Search SESSION 9. Programming Languages for Objects

Transcription:

The Collections API Mark Allen Weiss Lecture Objectives 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 2 The Collections API New in Java 1.2 (download for Java 1.1 available from Sun). Contains new data structures including linked list, queue, set, and map. Contains generic algorithms including sorting. Mostly in java.util. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 3 1

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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 4 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 5 Basic Supporting Interfaces There are some new supporting interfaces. The four most important are: Collection Iterator Comparable Comparator Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 6 2

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( ) Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 7 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 elements. next returns the next element (and advances the iterator). remove removes the last element accessed. Officially preferred over Enumeration. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 8 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 9 3

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 will have a conflict in Java 1.2!) Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 10 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-existant ordering) for collections that are sorted. Similar to the function object in STL. Predefined constant function object is Collections.REVERSE_ORDER. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 11 Example of Comparator Sorting strings by length. Need to provide a comparison object. static void sortlistofstringsbylength( List L ) final class Comp implements Comparator public int compare( Object lhs, Object rhs ) return ((String)lhs).length( ) - ((String)rhs).length( ); Collections.sort( L, new Comp( ) ); Note: latest version uses stable mergesort. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 12 4

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. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 13 Data Structures Several data structures List, with list iterator Stack and Queue Set Map Not synchronized. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 14 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 15 5

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, but only by a constant amount (giving inefficient performance). Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 16 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. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 17 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 18 6

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. Yuck! Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 19 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, as in Java 1.1. String hashcode is fixed in Java 1.2. TreeSet is a sorted-order (red-black tree version). It appeared in Java 1.2 Beta 3. Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 20 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 21 7

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 entries( ) Each key/value entry is of the type Map.Entry. Use getkey and getvalue on the Map.Entry object. Copyright 1996, 1999, M. A. Weiss 22 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 23 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] ) ); TreeMap 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, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 24 8

Concordance Code: Part II while( st.hasmoretokens( ) ) String word = st.nexttoken( ); LinkedList lines = (LinkedList) wordmap.get( word ); if( lines == null ) lines = new LinkedList( ); wordmap.put( word, lines ); lines.addlast( new Integer( linenum ) ); // Go through the word map Iterator itr = wordmap.entries( ).iterator( ); while( itr.hasnext( ) ) printentry( (Map.Entry) itr.next( ) ); catch( Exception e ) System.err.println( e ); Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 25 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 = ((LinkedList)(entry.getValue())).iterator(); System.out.print( "\t" + itr.next( ) ); while( itr.hasnext( ) ) System.out.print( ", " + itr.next( ) ); System.out.println( ); Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 26 Synchronization Use a Collections wrapper. Must manually synchronize iterators. Not pretty; needs work. Map m = Collections.synchronizedMap(new TreeMap());... synchronized(m) Iterator itr = m.iterator(); while (itr.hasnext()) foo(itr.next(); Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 27 9

Summary Collections API has some power, but is still a work in progress. Needs: Priority Queue Efficient synchronized algorithms Tuesday, December 07, 1999 Copyright 1996, 1999, M. A. Weiss 28 10