AD 300 ---- Lecture #3 Java Collection Framework 1.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
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.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
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.
Data Structures & Java Collections Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Sets and Maps Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
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.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
The Java Collections Framework (JCF) Introduction and review 1.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Big Java Chapter 16.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Chapter 18 Java Collections Framework
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections –data structures and Algorithms L. Grewe.
Data structures and algorithms in the collection framework 1.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
1 Interfaces in Java’s Collection Framework Rick Mercer.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
13 Collections Framework. 2 Contents What is Collection? Collections Framework Collections Hierarchy Collections Implementations Set List Map.
Set and Map IS 313, Skeletons  Useful coding patterns  Should understand how and why they work how to use  possible quiz material.
Priority Queues. Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue.
Maps Nick Mouriski.
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.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
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.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Using the Java Collection Libraries COMP 103 # T2
Chapter 19 Java Data Structures
Road Map CS Concepts Data Structures Java Language Java Collections
CSE 1020: The Collection Framework
Introduction to Collections
Presentation transcript:

AD Lecture #3 Java Collection Framework 1

Java collections framework

3 Interfaces Root interface for operations common to all types of collections Specialises collection with operations for FIFO and priority queues. Stores a sequence of elements, allowing indexing methods A special Collection that cannot contain duplicates. Special Set that retains ordering of elements. Stores mappings from keys to values Special map in which keys are ordered Generalisation Specialisation Collection SetListQueue SortedSet Map SortedMap

4 Expansion of contracts +add(E):boolean +remove(Object):boolean +contains(Object):boolean +size():int +iterator():Iterator etc… > Collection +add(E):boolean +remove(Object):boolean +get(int):E +indexOf(Object):int +contains(Object):boolean +size():int +iterator():Iterator etc… > List +add(E):boolean +remove(Object):boolean +contains(Object):boolean +size():int +iterator():Iterator etc… > Set

5 java.util.Iterator Think about typical usage scenarios for Collections Retrieve the list of all patients Search for the lowest priced item More often than not you would have to traverse every element in the collection – be it a List, Set, or your own datastructure Iterators provide a generic way to traverse through a collection regardless of its implementation a f g d b c e i h a b cdefg h i a b cdefg h i Iterator next():d iterator() Set List hasNext()?

Using an Iterator Quintessential code snippet for collection iteration: public void list(Collection items) { Iterator it = items.iterator(); while(it.hasNext()) { Item item = it.next(); System.out.println(item.getTitle()); } +hasNext():boolean +next():E +remove():void > Iterator Design notes: nAbove method takes in an object whose class implements Collection nList, ArrayList, LinkedList, Set, HashSet, TreeSet, Queue, MyOwnCollection, etc nWe know any such object can return an Iterator through method iterator() nWe don’t know the exact implementation of Iterator we are getting, but we don’t care, as long as it provides the methods next() and hasNext() nGood practice: Program to an interface!

7 java.lang.Iterable This is called a “for-each” statement For each item in items This is possible as long as items is of type Iterable Defines single method iterator() Collection (and hence all its subinterfaces) implements Iterable You can do this to your own implementation of Iterable too! To do this you may need to return your own implementation of Iterator Iterator it = items.iterator(); while(it.hasNext()) { Item item = it.next(); System.out.println(item); } for (Item item : items) { System.out.println(item); } = > Iterable +iterator():Iterator Collection MyBag List Set etc

8 Set Mathematical Set abstraction – contains no duplicate elements i.e. no two elements e1 and e2 such that e1.equals(e2) +add(E):boolean +remove(Object):boolean +contains(Object):boolean +isEmpty():boolean +size():int +iterator():Iterator etc… > Set remove(c)  true a b c d remove(x)  false add(x)  true a b c d x add(b)  false contains(e)  true ? contains(x)  false a b c d e isEmpty()  false size()  5

9 HashSet Typically used implementation of Set. Hash? Implemented using HashMap (later) Parameterise Sets just as you parameterise Lists Efficient (constant time) insert, removal and contains check – all done through hashing x and y are duplicates if x.equals(y) How are elements ordered? Quiz: Set words = new HashSet (); words.add("Bats"); words.add("Ants"); words.add("Crabs"); words.add("Ants"); System.out.println(words.size()); for (String word : words) { System.out.println(word); } ? a)Bats, Ants, Crabs b)Ants, Bats, Crabs c)Crabs, Bats, Ants d)Nondeterministic +add(E):boolean +remove(Object):boolean +contains(Object):boolean +size():int +iterator():Iterator etc… > Set HashSet 3

TreeSet ( SortedSet ) If you want an ordered set, use an implementation of a SortedSet: TreeSet What’s up with “Tree”? Red-black tree Guarantees that all elements are ordered (sorted) at all times add() and remove() preserve this condition iterator() always returns the elements in a specified order Two ways of specifying ordering Ensuring elements have natural ordering ( Comparable ) Giving a Comparator to the constructor Caution: TreeSet considers x and y are duplicates if x.compareTo(y) == 0 (or compare(x,y) == 0)

11 TreeSet construction String has a natural ordering, so empty constructor Set words = new TreeSet (); words.add("Bats"); words.add("Ants"); words.add("Crabs"); for (String word : words) { System.out.println(word); } Set albums = new TreeSet (new PriceComparator()); albums.add(new CD("Street Signs","O",new Money(3,50))); albums.add(new CD("Jazzinho","J",new Money(2,80))); albums.add(new CD("Space Cowboy","J",new Money(5,00))); albums.add(new CD("Maiden Voyage","HH",new Money(4,00))); albums.add(new CD("Here’s the Deal","LS",new Money(2,80))); System.out.println(albums.size()); for (CD album : albums) { System.out.println(album); } nBut CD doesn’t, so you must pass in a Comparator to the constructor What’s the output? 4 Jazzinho; Street; Maiden; Space What’s the output? Ants; Bats; Crabs

12 Map Stores mappings from (unique) keys (type K ) to values (type V ) See, you can have more than one type parameters! Think of them as “arrays” but with objects (keys) as indexes Or as “directories”: e.g. "Bob"  put(K,V):V +get(Object):V +remove(Object):V +size():int +keySet():Set +values():Collection etc… > Map get(k)  a a b c b k m p n get(x)  null keysvalues put(x,e)  null a b c b k m p n ex put(k,f)  a a b c b k m p n f size()  4 remove(n)  b remove(x)  null a b c b k m p n keySet()  Set k m p n values()  Collection a b cb

13 HashMap aka Hashtable (SE250) keys are hashed using Object.hashCode() i.e. no guaranteed ordering of keys keySet() returns a HashSet values() returns an unknown Collection +put(K,V):V +get(Object):V +remove(Object):V +size():int +keySet():Set +values():Collection etc… > Map HashMap Map directory = new HashMap (); directory.put("Mum", new Integer( )); directory.put("Dad", ); directory.put("Bob", ); directory.put("Edward", ); directory.put("Bob", ); System.out.println(directory.size()); for (String key : directory.keySet()) { System.out.print(key+"'s number: "); System.out.println(directory.get(key)); } System.out.println(directory.values()); 4 or 5? Set “autoboxing” What’s Bob’s number?

14 TreeMap Guaranteed ordering of keys (like TreeSet) In fact, TreeSet is implemented using TreeMap Hence keySet() returns a TreeSet values() returns an unknown Collection – ordering depends on ordering of keys Map directory = new TreeMap (); directory.put("Mum", new Integer( )); directory.put("Dad", ); directory.put("Bob", ); directory.put("Edward", ); directory.put("Bob", ); System.out.println(directory.size()); for (String key : directory.keySet()) { System.out.print(key+"'s #: "); System.out.println(directory.get(key)); } System.out.println(directory.values()); Loop output? Bob's #: Dad's #: Edward's #: Mum's #: ? Empty constructor  natural ordering