(c) University of Washington14-1 CSC 143 Java Collections.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
15-Jun-15 Lists in Java Part of the Collections Framework.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Chapter 19 Java Data Structures
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Java's Collection Framework
Java Collections Framework A presentation by Eric Fabricant.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading:
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CSC 142 P 1 CSC 142 Collections [Reading: Chapter 10]
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Copyright 2010 by Pearson Education Building Java Programs Chapter 10, 11 Lecture 22: 143 Preview optional reading: 10.1,
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
AD Lecture #3 Java Collection Framework 1.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Collections Dwight Deugo Nesa Matic
CSE 143 Lecture 11: Sets and Maps reading:
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Slides by Donald W. Smith
Using the Java Collection Libraries COMP 103 # T2
Chapter 19 Java Data Structures
Data Structures Lakshmish Ramaswamy.
Road Map CS Concepts Data Structures Java Language Java Collections
Introduction to Collections
Introduction to Collections
Presentation transcript:

(c) University of Washington14-1 CSC 143 Java Collections

(c) University of Washington14-2 Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of the OO approach to design and implementation identify common patterns regularize interface to increase commonality factor them out into common interfaces, abstract classes Their implementation will raise issues previously swept under the rug: efficiency

(c) University of Washington14-3 Goals for Next Several Lectures Survey different kinds of collections, focusing on their interfaces Lists, sets, maps Iterators over collections Then look at different possible implementations Arrays, linked lists, hash tables, trees Mix-and-match implementations to interfaces Compare implementations for efficiency How do we measure efficiency? Implementation tradeoffs

(c) University of Washington14-4 Java 2 Collection Interfaces Key interfaces in Java 1.2 and above: Collection – a collection of objects List extends Collection – ordered sequence of objects (first, second, third, …); duplicates allowed Set extends Collection – unordered collection of objects; duplicates suppressed Map – collection of pairs; each key may appear only once in the collection; item lookup is via key values (Think of pairs like,,, etc.) Iterator – provides element-by-element access to collection items

(c) University of Washington14-5 Java 2 Collection Implementations Main concrete implementations of these interfaces: ArrayList implements List (using arrays underneath) LinkedList implements List (using linked lists) HashSet implements Set (using hash tables) TreeSet implements Set (using trees) HashMap implements Map (using hash tables) TreeMap implements Map (using trees)

(c) University of Washington14-6 Java 5.0: Generics Before Java 5.0, the static type of the elements of a Collection or of the keys and values of a Map was Object Yields unattractive code ArrayList a = new ArrayList(); a.add("First element"); // a string String s = (String) a.get(0); // need a cast In Java 5.0, a Collection (or a Map) specifies the static type of its elements Better code ArrayList a = new ArrayList (); a.add("First element"); String s = a.get(0); // no cast With Generics, the compiler can do some type checking. ArrayList a = new ArrayList (); a.add(new Oval()); // doesn’t compile

(c) University of Washington14-7 Java 5.0: Boxing Before Java 5.0, a primitive type could not be put directly in a collection ArrayList a = new ArrayList(); int i = 3; a.add(i);// NO! a.add(new Integer(i)); // OK The distinction between primitive and reference types is still present in Java 5.0. But, the details are hidden from the programmer. ArrayList a = new ArrayList (); int i = 3; a.add(i);// OK: i is boxed into an Integer object int k = a.get(0); // OK: the arraylist element is unboxed

(c) University of Washington14-8 interface Collection Basic methods available on most collections (E is the generic type of the collection): int size ( ) – # of items currently in the collection boolean isEmpty ( ) – (size( ) == 0) boolean contains (Object o) – true if o is in the collection [how to compare o with the elements already in the collection?] boolean add (E o) – ensure that o is in the collection, possibly adding it; return true if collection altered; false if not. [leaves a lot unspecified….] boolean addAll (Collection other) – add all elements in the other collection (actually not the exact signature…) boolean remove (Object o) – remove one o from the collection, if present; return true if something was actually removed void clear ( ) – remove all elements Iterator iterator ( ) – return an iterator object for this collection

(c) University of Washington14-9 interface Iterator Provides access to elements of any collection one-by-one, even if the collection has no natural ordering (sets, maps) boolean hasNext ( ) – true if the iteration has more elements E next ( ) – next element in the iteration; precondition: hasNext( ) == true void remove ( ) – remove from the underlying collection the element last returned by the iteration. [Optional; some collections don’t support this.]

(c) University of Washington14-10 Standard Iterator Loop Pattern Collection c = …; Iterator iter = c.iterator( ); while (iter.hasNext( )) { E elem = iter.next( ); // do something with elem } Note similarity to generic file/stream processing loop: open stream -- perhaps from file while not at end of stream { read/write next data item, do something with it }

(c) University of Washington14-11 Iterators vs. Counter Loops A related pattern is the counting loop : ArrayList list = …; for (int i = 0; i < list.size( ); i ++) { E elem = list.get(i); // do something with elem } The iterator pattern is generally preferable because it... works over any collection, even those without a get(int) operation encapsulates the tedious details of iterating, indexing

(c) University of Washington14-12 Still more abstraction: for( : ) Can even use an iterator without asking for one ArrayList list = …; for (E elem : list) { // do something with elem } CSC143 style rule: use the iterator pattern (with an actual iterator or in the form of the above for loop). It is a good illustration of the concept of abstraction. Unless there are compelling reasons to use a counting loop (e.g. initialization) Note: the for( : ) statement works for arrays as well (anything that is Iterable) int a = new int [10]; for ( int k : a) { // do something with k }

(c) University of Washington14-13 Lists as Collections In some collections, there is no natural order Leaves on a tree, grocery items in a bag, grains of sand on the beach In other collections, the order of elements is natural and important Chapters of a book, floors in a building, people camping out to buy Starwars tickets Lists are collections where the elements have an order Each element has a definite position (first, second, third, …) positions are generally numbered from 0

(c) University of Washington14-14 interface List extends Collection Following are included in all Java Lists (and some other Collection types): E get ( int pos) – return element at position pos boolean set ( int pos, E elem) – store elem at position pos boolean add ( int pos, E elem) – store elem at position pos; slide elements at position pos to size( )-1 up one position to the right E remove ( int pos) – remove item at given position; shift remaining elements to the left to fill the gap; return the removed element int indexOf (Object o) – return position of first occurrence of o in the list, or -1 if not found Precondition for most of these is 0 <= pos < size( )

(c) University of Washington14-15 interface ListIterator extends Iterator The iterator( ) method for a List returns an instance of ListIterator Can also send listIterator (int pos) to get a ListIterator starting at the given position in the list ListIterator returns objects in the list collection in the order they appear in the collection Supports additional methods: hasPrevious ( ), previous ( ) – for iterating backwards through a list set ( E o) – to replace the current element with something else add ( E o) – to insert an element after the current element

(c) University of Washington14-16 List Implementations ArrayList – internal data structure is an array Fast iterating Fast access to individual elements (using get(int), set(int, E)) Slow add/remove, particularly in the middle of the list LinkedList – internal data structure is a linked list Fast iterating Slow access to individual elements (using get(int), set(int, E)) Fast add/remove, even in the middle of the list if via iterator A bit later in the course we’ll dissect both forms of implementation

(c) University of Washington14-17 interface Set extends Collection As in math, a Set is an unordered collection, with no duplicate elements attempting to add an element already in the set does not change the set Interface is same as Collection, but refines the specifications The specs are in the form of comments interface SortedSet extends Set Same as Set, but iterators will always return set elements in a specified order Requires that elements be Comparable: implement the compareTo (E o) method, returning a negative, 0, or positive number to mean =, respectively or that elements be comparable with a Comparator.

(c) University of Washington14-18 interface Map Collections of pairs keys are unique, but values need not be Doesn't extend Collection, but does provide similar methods size ( ), isEmpty ( ), clear ( ) Basic methods for dealing with pairs: V put (K key, V value) – add to the map, replacing the previous mapping if one exists void putAll (Map other) – put all pairs from other into this map V get (K key) – return the value associated with the given key, or null if key is not present V remove (K key) – remove any mapping for the given key boolean containsKey (Object key) – true if key appears in a pair boolean containsValue (Object value) – true if value appears in a

(c) University of Washington14-19 Maps and Iteration Map provides methods to view contents of a map as a collection: Set keySet( ) – return a Set whose elements are the keys of this map Collection values( ) – return a Collection whose elements are the values contained in this map [why is one a set and the other a collection?] To iterate through the keys or values or both, grab one of these collections, and then iterate through that Map map = …; Set keys = map.keySet( ); for (K key : keys) { V value = map.get(key); // do something with key and value }

(c) University of Washington14-20 interface SortedMap extends Map SortedMap can be used for maps where we want to store key/value pairs in order of their keys Requires keys to be Comparable, using compareTo, or comparable with a Comparator. Sorting affects the order in which keys and values are iterated through keySet( ) returns a SortedSet values( ) returns an ordered Collection

(c) University of Washington14-21 Preview of Coming Attractions 1.Study ways to implement these interfaces Array-based vs. link-list-based vs. hash-table-based vs. tree- based 2.Compare implementations What does it mean to say one implementation is “faster” than another? Basic complexity theory – O( ) notation 3.Use these and other data structures in our programming