Java's Collection Framework

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:
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.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
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 
Working With Collections in the AP ™ Java Subset 2003 ACTE Convention © 2003 by Kenneth A. Lambert.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
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.
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.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
1 ADTs, Collection, Iterable/Iterator Interfaces Collections and the Java Collections API The Collection Interface and its Hierarchy The Iterable and Iterator.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Chapter 19 Java Data Structures
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
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.
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.
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 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
תוכנה 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.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
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.
SETS AND MAPS Collections of Data. Advanced Data Structures Often referred to as the Java Collections Framework…. Set and map data types Hash tables Binary.
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.
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.
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.
List data type(ADT). Lists Elements : a 1,a 2,a 3,… a i-1,a i, a i+1,…a n Null List contains: 0 elements Types of Operations on list 1.Insertion 2.Deletion.
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.
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
University of Limerick1 Collections The Collection Framework.
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
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Using the Java Collection Libraries COMP 103 # T2
Java's Collection Framework
Chapter 19 Java Data Structures
Interfaces in Java’s Collection Framework
Introduction to Collections
JAVA Collections Framework Set Interfaces & Implementations
Introduction to Collections
Introduction to Collections
Introduction to Collections
Presentation transcript:

Java's Collection Framework

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

Collection interfaces in java.util Image from the Java Tutorial

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 implementations Which Java construct nicely specifies ADTs?

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 Java has many collection classes including: ArrayList<E> LinkedList<E> LinkedBlockingQueue<E> ArrayBlockingQueue<E> Stack<E> HashSet<E> TreeSet<E> HashMap<K,V> TreeMap<K,V>

Common Functionality Collection classes often have methods for Adding objects Removing an object Finding a reference to a particular object We can then send messages to the object still referenced by the collection

The Collection Interface interface Collection abstractly describes a bag, or multi-set Some classes implementing Collection allow duplicate elements; others do not keeps elements ordered; others do not

Why have interface Collection? Collection allows different types of objects to be treated the same It is used to pass around collections of objects with maximum generality for example addAll(Collection<? extends E> c) This method adds all of the elements in the specified collection in an appropriate way Can add all elements of a Stack to a Queue, or add all elements of a Set to a List

Why have interface Collection? With this method, we can iterate over all Collections using hasNext and Next Iterator<E> iterator() With this method, we can find out if all the elements in a set are in a list or queue boolean containsAll(Collection<?> c)

Collection method signatures The methods of interface Collection http://java.sun.com/javase/7/docs/api/java/util/Collection.html boolean add(E e) boolean addAll(Collection<? extends E> c) void clear() boolean contains(Object o) boolean containsAll(Collection<?> c) boolean equals(Object o) int hashCode() boolean isEmpty() Iterator<E> iterator() boolean remove(Object o) boolean removeAll(Collection<?> c) boolean retainAll(Collection<?> c) int size() Object[] toArray()

One Interface Note: List extends Collection List: a collection where indexes matter extends Collection so it has all of the methods of Collection Can decide where in the List elements are inserted

List<E>, an Abstract Data Type (ADT) written as a Java interface List<E>: a collection with a first element, a last element, distinct predecessors and successors The user of this interface has precise control over where in the list each element is inserted duplicates that "equals" each other are allowed

List<E> Users of the interface List<E> have precise control over where in the list each element is inserted. allows programmers to access elements by their integer index (position in the list) search for elements in the list Can have duplicate elements (equals) Methods include: add, addAll, indexOf, isEmpty, remove, toArray Some implementing classes in java.util: ArrayList<E>, LinkedList<E>, Stack<E>, Vector<E>

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

Iterate over different lists the same way List<Integer> arrayL = new ArrayList<Integer>(); List<Integer> linkedL = new LinkedList<Integer>(); for (int num = 1; num <= 12; num += 2) { arrayL.add(num); linkedL.add(num + 1); } Iterator<Integer> arrayItr = arrayL.iterator(); Iterator<Integer> linkedItr = linkedL.iterator(); while (arrayItr.hasNext()) System.out.print(arrayItr.next() + " "); System.out.println(); while (linkedItr.hasNext()) System.out.print(linkedItr.next() + " "); Output: 1 3 5 7 9 11 2 4 6 8 10 12

Polymorphism via interfaces The previous slides shows different types treated as type List, all three implement interface List understand the same messages have different methods with the same names execute All classes have add, get, iterator This is an example of polymorphism via interfaces

Stack<E> void push(E e) Adds e to the top of the stack boolean isEmpty() Return true if the has no elements E peek() Retrieves, but does not remove, the element at the top of this queue E pop() Retrieves and removes the element at the top of this stack

Queue<E> 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

ArrayBlockingQueue<E> a FIFO queue ArrayBlockingQueue<Double> numberQ = new ArrayBlockingQueue<Double>(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());

TreeSet implements Set Set<E> An interface for collections with no duplicates. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2) TreeSet<E>: 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<T>

TreeSet elements are in order SortedSet<Integer> set = new TreeSet<Integer>(); set.add(7); set.add(2); set.add(8); set.add(9); System.out.println(set); System.out.println(set.tailSet(8)); System.out.println(set.headSet(8)); System.out.println(set.subSet(1, 9)); [2, 7, 8, 9] [8, 9] [2, 7] [2, 7, 8]

HashSet elements are not in order Set<String> names = new HashSet<String>(); names.add("Devon"); names.add("Sandeep"); names.add("Chris"); names.add("Kim"); names.add("Chris"); // not added Iterator<String> itr = names.iterator(); while (itr.hasNext()) System.out.print(itr.next() + " "); Output: Sandeep Chris Devon Kim

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 Concrete classes in java.util HashMap<K, V> and TreeMap<K, V>

Map Operations java.util.HashMap<K, V> public V put(K key, V value) associates key to value and stores mapping public V get(K key) associates the value to which key is mapped or null public boolean containsKey(K key) returns true if the Map already uses the key public V remove(K key) public Collection<V> values() get a collection you can iterate over public Collection<V> keySet()

Using a Map Map<String, BankAccount> aMap= new TreeMap<String, BankAccount>(); BankAccount acct1 = new BankAccount("Jessica", 500.00); BankAccount acct2 = new BankAccount("Alex", 400.00); BankAccount acct3 = new BankAccount("Anthony", 300.00); BankAccount acct4 = new BankAccount("Danny", 200.00); aMap.put(acct1.getID(), acct1); aMap.put(acct2.getID(), acct2); aMap.put(acct3.getID(), acct3); aMap.put(acct4.getID(), acct4); // Check out the keys and the value in aMap Collection<String> keys = aMap.keySet(); System.out.println(keys); Collection<BankAccount> values = aMap.values(); System.out.println(values); Output [Alex, Anthony, Danny, Jessica] [Alex $400.0, Anthony $300.0, Danny $200.0, Jessica $500.0]