3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.

Slides:



Advertisements
Similar presentations
Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
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.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
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.
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
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
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.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
(c) University of Washington14-1 CSC 143 Java Collections.
3-1 Polymorphism with Java Interfaces Rick Mercer.
1 Sets and Maps Starring: keySet Co-Starring: 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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
COLLECTIONS Byju Veedu s/Collection.html.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Object Oriented Programming Ders 10: Data Structures Mustafa Emre İlal
Chapter 18 Java Collections Framework
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Data structures Abstract data types Java classes for Data structures and ADTs.
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.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
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.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
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.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
University of Limerick1 Collections The Collection Framework.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
Collections Dwight Deugo Nesa Matic
CSE 143 Lecture 11: Sets and Maps reading:
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Using the Java Collection Libraries COMP 103 # T2
Java's Collection Framework
Chapter 19 Java Data Structures
Interfaces in Java’s Collection Framework
Road Map CS Concepts Data Structures Java Language Java Collections
Java Collections Overview
Introduction to Collections
Polymorphism with Java Interfaces
CSE 1020: The Collection Framework
Presentation transcript:

3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer

3-2 Outline  Java's Collection Framework — Unified architecture for representing and manipulating collections  Collection framework contains — Interfaces (ADTs): specification not implementation — Concrete implementations as classes — Polymorphic Algorithms to search, sort, find, shuffle,...  Algorithms are polymorphic: — the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.

3-3 Collection interfaces in java.util Image from the Java Tutorial

3-4 Abstract Data Type  Abstract data type (ADT) is a specification of the behaviour (methods) of a type — Specifies method names to add, remove, find — Specifies if elements are unique, indexed, accessible from only one location, mapped,... — An ADT shows no implementation no structure to store elements, no implemented algorithms  What Java construct nicely specifies ADTs?

3-5 Collection Classes  A collection class the can be instantiated — implements an interface as a Java class — implements all methods of the interface — selects appropriate instance variables  Since Java 5: we have concrete collection classes — Stack — ArrayList, LinkedList — LinkedBlockingQueue, ArrayBlockingQueue — HashSet, TreeSet — TreeMap, HashMap

3-6 Common Functionality  Collection classes often have methods for — Adding objects — Removing an object — Finding a reference to a particular object find can then send messages to the object still in the collection

3-7 List, an ADT written as a Java interface review for some  List : a collection with a first element, a last element, distinct predecessors and successors List — The user of this interface has precise control over where in the list each element is inserted — duplicates that " equals " each other are allowed  The List interface is implemented by these three collection classes — ArrayList ArrayList — LinkedList LinkedList — Vector Vector

3-8 import java.util.*; // For List, ArrayList, Linked... import static org.junit.Assert.*; import org.junit.Test; public class ThreeClassesImplementList public void showThreeImplementationsOfList() { // Interface name: List // Three classes that implement the List interface: List bigList = new ArrayList (); List littleList = new LinkedList (); List sharedList = new Vector (); // All three have an add method bigList.add("in array list"); littleList.add("in linked list"); sharedList.add("in vector"); // All three have a get method assertEquals("in array list", bigList.get(0)); assertEquals("in linked list", littleList.get(0)); assertEquals("in vector", sharedList.get(0)); }

3-9 Iterators  Iterators provide a general way to traverse all elements in a collection ArrayList list = new ArrayList (); list.add("1-FiRsT"); list.add("2-SeCoND"); list.add("3-ThIrD"); Iterator itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next().toLowerCase()); } Output 1-first 2-second 3-third

3-10 New way to visit elements: Java's Enhanced for Loop  The for loop has been enhanced to iterate over collections  General form for (Type element : collection) { element is the next thing visited each iteration } for (String str : list) { System.out.println(str + " "); }

3-11 Can't add the wrong type  Java 5 generics checks the type at compile time — See errors early--a good thing — "type safe" because you can't add different types ArrayList dates = new ArrayList (); dates.add(new GregorianCalendar()); // Okay dates.add("String not a GregorianCalendar"); // Error ArrayList ints = new ArrayList (); ints.add(1); // Okay. Same as add(new Integer(1)) ints.add("Pat not an int")); // Error

3-12 Algorithms  Java has polymorphic algorithms to provide functionality for different types of collections — Sorting (e.g. sort) Sorting — Shuffling (e.g. shuffle) Shuffling — Routine Data Manipulation (e.g. reverse, addAll) Routine Data Manipulation — Searching (e.g. binarySearch) Searching — Composition (e.g. frequency) Composition — Finding Extreme Values (e.g. max) Finding Extreme Values  Static methods in the Collections class  Demo a few of these with ArrayList

3-13 TreeSet implements Set  Set An interface for collections with no duplicates. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2) Set  TreeSet : This class implements the Set interface, backed by a balanced binary search tree. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements as defined by Comparable TreeSet

3-14 Set and SortedSet  The Set interface — add, addAll, remove, size, but no get!  Two classes that implement Set — TreeSet: values stored in order, O(log n) — HashSet: values in a hash table, no order, O(1)  SortedSet extends Set by adding methods E first(), SortedSet tailSet(E fromElement), SortedSetE SortedSet headSet(E fromElement), E last(), SortedSet subSet(E fromElement, E toElement)SortedSetE SortedSetE

3-15 TreeSet elements are in order Set names = new TreeSet (); names.add("Sandeep"); names.add("Chris"); names.add("Kim"); names.add("Chris"); // not added names.add("Devon"); for (String name : names) System.out.println(name);  Output?  Change to HashSet

3-16 The Map Interface (ADT)  Map describes a type that stores a collection of elements that consists of a key and a value  A Map associates (maps) a key the it's value  The keys must be unique — the values need not be unique — put destroys one with same key

3-17 Map Operations  Java's HashMap HashMap — public V put(K key, V value) associates key to value and stores mapping — public V get(Object key) associates the value to which key is mapped or null — public boolean containsKey(Object key) returns true if the Map already uses the key — public V remove(Object key) Returns previous value associated with specified key, or null if there was no mapping for key. — Collection values() get a collection you can iterate over

3-18 Code Demo Rick: Put in a file named HashMapDemo.java  Add some mappings to a HashMap and iterate over all elements with Collection values() and all keys with Set keySet()

3-19 Queue boolean add(E e) Inserts e into this queue E element() Retrieves, but does not remove, the head of this queue boolean offer(E e) Inserts e into this queue E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty E remove() Retrieves and removes the head of this queue

3-20 ArrayBlockingQueue a FIFO queue ArrayBlockingQueue numberQ = new ArrayBlockingQueue (40); numberQ.add(3.3); numberQ.add(2.2); numberQ.add(5.5); numberQ.add(4.4); numberQ.add(7.7); assertEquals(3.3, numberQ.peek(), 0.1); assertEquals(3.3, numberQ.remove(), 0.1); assertEquals(2.2, numberQ.remove(), 0.1); assertEquals(5.5, numberQ.peek(), 0.1); assertEquals(3, numberQ.size());