Lecture 6 Collections

Similar documents
Java Collections Framework reloaded

CONTAİNERS COLLECTİONS

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

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

Sets and Maps. Part of the Collections Framework

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

Java Collections Framework: Interfaces

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

CSC 1214: Object-Oriented Programming

Class 32: The Java Collections Framework

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

Generics and collections

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

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

Collections Framework: Part 2

Generics Collection Framework

What is the Java Collections Framework?

Collections Questions

Algorithms. Produced by. Eamonn de Leastar

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.

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

CS Ananda Gunawardena

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

9/16/2010 CS Ananda Gunawardena

Collections (Java) Collections Framework

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

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

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

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

Tha Java Programming Language

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

An Interface with Generics

A simple map: Hashtable

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Java Collection Framework

Collections. The Java Collections Framework. The Interfaces

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

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

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

Basicsof programming3. Java collections

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

The Java Collections Framework. Chapters 7.5

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList!

Introduction to Collections

Lecture 4. The Java Collections Framework

CS11 Java. Winter Lecture 8

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.

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

Get started with the Java Collections Framework By Dan Becker

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

Framework in Java 5. DAAD project Joint Course on OOP using Java

Generic Programming. *Really* reusable code

Collections. James Brucker

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

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

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

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

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

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

Lecture 16: Case Study: The Java Collections API

Java Collections Framework. 24 April 2013 OSU CSE 1

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

DM550 Introduction to Programming part 2. Jan Baumbach.

CS2110: Software Development Methods. Maps and Sets in Java

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

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

CS2110: Software Development Methods. Maps and Sets in Java

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

Collections. Other references:

Computer Science II (Spring )

Fundamental language mechanisms

Chapter 10 Collections

CSE 143. Computer Programming II

Overview of Java s Support for Polymorphism

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

To describe the Java Collections Framework. To use the Iterator interface to traverse a. To discover the Set interface, and know how

EECS 2011 M: Fundamentals of Data Structures

boolean add(object o) Method Description (from docs API ) Method Description (from docs API )

Java Collections Framework

CSD Univ. of Crete Fall The Java Collection Framework: Interfaces, Classes, and Algorithms

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

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

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

CSE 143 Au03 Midterm 2 Sample Solution Page 1 of 7

CS61B Lecture #17. Administrative: Need alternative test time? Make sure you send me mail.

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Topics. CS61B Lecture #17. Collection Structures in java.util. Data Types in the Abstract

JAVA. java.lang.stringbuffer java.lang.stringbuilder

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

USAL1J: Java Collections. S. Rosmorduc

Transcription:

Lecture 6 Collections Concept A collection is a data structure actually, an object to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util package! Lots of interfaces and classes providing a general collection framework. Programmers may also provide implementations specific to their own requirements Overview of the interfaces and concrete classes in the collection framework Collection Map Iterator Set List SortedMap HashMap WeakHashMap ListIterator SortedSet HashSet ArrayList LinkedList TreeMap TreeSet 1

Root interface Collection (1) Methods working with an individual collection public int size() public boolean isempty() public boolean contains(object elem) public boolean add(object elem) Depends on whether the collection allows duplicates public boolean remove(object elem) public boolean equals(object o) public int hashcode() public Iterator iterator() public Object[] toarray() Returns a new array containing references to all the elements of the collection public Object[] toarray(object[] dest) What is returned depends on whether the elements in the collection fit in dest If the type of dest is not compatible with the types of all elements in the collection, an exception is thrown Root interface Collection (2) Primary methods operating in bulk from another collection public boolean containsall(collection coll) public boolean addall(collection coll) Returns true if any addition succeeds public boolean removeall(collection coll) Returns true if any removal succeeds public boolean retainall(collection coll) Removes from the collection all elements that are not elements of coll public void clear() Remove all elements from this collection The SDK does NOT provide any direct implementations of the Collection interface Most of the actual collection types implement this interface, usually by implementing an extended interface such as Set or List This interface is typically used to pass collections around and manipulate them where maximum generality is desired. 2

Iteration - Iterator The Collection interface defines an iterator method to return an object implementing the Iterator interface. It can access the elements in a collection without exposing its internal structure. There are NO guarantees concerning the order in which the elements are returned Three defined methods in Iterator interface public boolean hasnext() returns true if the iteration has more elements public Object next() returns the next element in the iteration An exception will be thrown if there is no next element What s returned is an Object object. You may need special casting! public void remove() remove from the collection the element last returned by the iteration can be called only once per call of next, otherwise an exception is thrown classical routine of using iterator: public void removelongstrings (Collection coll, int maxlen) { Iterator it = coll.iterator(); while ( it.hasnext() ) { String str = (String)it.next(); if (str.length() > maxlen) it.remove() 3

Iteration - ListIterator ListerIterator interface extends Iterator interface. It adds methods to manipulate an ordered List object during iteration Methods public boolean hasnext()/ public boolean hasprevious() public Object next()/ public Object previous() public Object nextindex()/ public Object previousindex() When it s at the end of the list, nextindex() will return list.size() When it s at the beginning of the list, previousindex() will return -1 public void remove() remove the element last returned by next() or previous() public void add(object o) insert the object o into the list in front of the next element that would be returned by next(), or at the end if no next element exists public void set(object o) set the element last returned by next() or previous() with o Potential problem of Iterator/ListIterator They do NOT provide the snapshot guarantee if the content of the collection is modified when the iterator is in use, it can affect the values returned by the methods import java.util.*; public class IteratorTest { public static void main (String args[]) { ArrayList a = new ArrayList(); a.add("1"); a.add("2"); a.add("3"); Iterator it = a.iterator(); while(it.hasnext()) { String s = (String)(it.next()); if(s.equals( 1")) { a.set(2, changed"); System.out.println(s); Output? 1 2 changed 4

Potential problem of Iterator/ListIterator (cont.) A snapshot will return the elements as they were when the Iterator/ListIterator object was created, which is unchangeable in the future If you really need a snapshot, you can make a simple copy of the collection Many of the iterators defined in the java.util package are in the type of fail-fast iterators They detect when a collection has been modified When a modification is detected, other than risk performing an action whose behavior may be unsafe, they fail quickly and cleanly by throwing an exception ConcurrentModificationException import java.util.*; public class IteratorTest2 { public static void main (String args[]) { ArrayList a = new ArrayList(); a.add( 1 ); a.add( 2 ); a.add( 3 ); Iterator it = a.iterator(); a.add( 4 ); while(it.hasnext()) { String s = (String)(it.next()); System.out.println(s); %> javac IteratorTest2.java %> java IteratorTest2 Exception in thread main java.util.concurrentmodificationexception 5

List A List is an ordered Collection which allows duplicate elements. Its element indices range from 0 to (list.size()-1) It adds several methods for an ordered collection The interface List is implemented by two classes 1. ArrayList: a resizable-array implementation of the List interface Adding or removing elements at the end, or getting an element at a specific position is simple O(1) Adding or removing element from the middle is more expensive O(n-i) Can be efficiently scanned by using the indices without creating an Iterator object, so it s good for a list which will be scanned frequently 2. LinkedList: a doubly-linked list Getting an element at position i is more expensive O(i) A good base for lists where most of the actions are not at the end An example of using LinkedList (output) Set and SortedSet The Set interface provides a more specific contract for its methods, but adding no new methods of its own. A Set is a Collection that contains UNIQUE elements. The SortedSet extends Set to specify an additional contract iterators on such a set will always return the elements in a specified order By default it will be the elements natural order which is determined by the implementation of Comparable interface You can specify a Comparator object to order the elements instead of the natural order There are two implementations of Set in the collection framework HashSet a Set implemented using a hashtable TreeSet a SortedSet implemented in a balanced tree structure An example of using a HashSet (output) 6

Map and SortedMap The Map interface does not extend Collection interface because a Map contains key-value pairs, not only keys. Duplicate keys are not allowed in a Map. It s implemented by classes HashMap and TreeMap. There are methods to view the map using collections. For example: public Set keyset() and public Collection values(). The collections returned by these methods are backed by the Map, so removing an element from one these collections removes the corresponding key/value pair from the map You cannot add elements to these collections If you iterate through the key or value sets, they may return values from their respective sets in any order Interface SortedMap extends Map and maintains its keys in sorted order. Class TreeMap implements SortedMap. An example using HashMap (output) Synchronized wrappers and the Collections class (1) The Collections class contains static utility methods which can be roughly classified into two groups: those provide wrapped collections and those don t. All the collection implementations provided in java.util we ve seen so far are unsynchronized concurrent access to a Collection by multiple threads could cause indeterminate results or fatal errors. you can use synchronization wrappers for those collections that might be accessed by multiple threads to prevent potential threading problems. Methods in the Collections class to get a synchronized wrapper Collection synchronizedcollection(collection c) Set synchronizedset(set s) SortedSet synchronizedsortedset(sortedset s) List synchronizedlist(list l) Map synchronizedmap(map m) SortedMap synchronizedsortedmap(sortedmap m) 7

Synchronized wrappers and the Collections class (2) The above methods return wrappers whose methods are fully synchronized, and so are safe to use from multiple threads Example Map unsyncmap = new HashMap(); Map syncmap = Collections.synchronizedMap(unSyncMap); unsyncmap HashMap elements syncmap synchronized wrapper synchmap has all relevant methods synchronized, passing all calls through to the wrapped map (unsynchmap) there is actually only one map, but with two different views. So modifications on either map is visible to the other the wrapper synchronizes on itself, so you can use syncmap to synchronize access, and then use unsyncmap safely inside such code synchronized (syncmap) { for (int i=0; i< keys.length; i++) unsyncmap.put ( keys[i], values[i] ); Unmodifiable wrappers and the Collections class (1) The Collections class contains a set of methods that return unmodifiable wrappers for collections: attempts to modify the returned set, whether direct or via its iterator, result in an UnsupportedOperationException The contents of an unmodifiable wrapper can change, but can only through the original collection, not through the wrapper itself Six methods to return unmodifable wrappers: Collection unmodifiablecollection(collection c) Set unmodifiableset(set s) SortedSet unmodifiablesortedset(sortedset s) List unmodifiablelist(list l) Map unmodifiablemap(map m) SortedMap unmodifiablesortedmap(sortedmap m) 8

Unmodifiable wrappers and the Collections class (2) Example Original: it s dangerous that the array s content can be changed public String suits[]= { Hearts, Clubs, Diamonds, Spades ; Using the unmodifiable wrapper to prevent the danger: private String suitsnames[] = { Hearts, Clubs, Diamonds, Spades ; public final List suits = Collections.unmodifiableList(Arrays.asList(suitNames ); The unmodifiable wrapper offers read-only access to others, while the read-write access is still available to the code itself by retaining a reference to the wrapped collection (the original collection) Abstract implementations The collection framework provides a set of abstract implementations for you to design your own implementation of relevant collection interfaces to satisfy your particular needs The set of abstract classes: AbstractCollection AbstractSet AbstractList AbstractSequentialList AbstractMap 9

The legacy collection types The package java.util contains some other legacy collections than those we just learned. They are still in wide use in existing code and will continue to be used until programmers shift over to the new types The set of legacy collections Enumeration analogous to Iterator Vector analogous to ArrayList Stack a subclass of Vector Dictionary analogous to Map interface Hashtable analogous to HashMap Properties a subclass of HashTable 10