Java's Collection Framework

Slides:



Advertisements
Similar presentations
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.
Advertisements

Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
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.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
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.
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.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Chapter 18 Java Collections Framework
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
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 Interfaces in Java’s Collection Framework Rick Mercer.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
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.
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.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Java Collections CHAPTER 3-February-2003
Slides by Donald W. Smith
Java Collections OOP tirgul No
Using the Java Collection Libraries COMP 103 # T2
תרגול 7 – מבני נתונים גנריים רובי בוים ומתי שמרת
Chapter 19 Java Data Structures
Wednesday Notecards. Wednesday Notecards Wednesday Notecards.
Software Development Java Collections
JAVA COLLECTIONS LIBRARY
Interfaces in Java’s Collection Framework
Road Map CS Concepts Data Structures Java Language Java Collections
structures and their relationships." - Linus Torvalds
Java Collections Overview
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
JAVA Collections Framework Set Interfaces & Implementations
TCSS 342, Winter 2006 Lecture Notes
Introduction to Collections
Introduction to Collections
Polymorphism with Java Interfaces
CSE 143 Lecture 27: Advanced List Implementation
Collections Not in our text.
"He's off the map!" - Eternal Sunshine of the Spotless Mind
Introduction to Collections
Collections Framework
CSE 373 Java Collection Framework, Part 2: Priority Queue, Map
CSE 1020: The Collection Framework
Introduction to Collections
Containers and Iterators
slides created by Marty Stepp
Building Java Programs
Data Structures II AP Computer Science
Part of the Collections Framework
CSE 143 Lecture 21 Advanced List Implementation
structures and their relationships." - Linus Torvalds
Java Generics & Iterators
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

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()

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 List to a Queue, or add all elements of a Set to a List, or add all elements of one List to another 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, or … boolean containsAll(Collection<?> c)

interface List extends interface 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>, many more

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

The enhanced for loop 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); } for (Integer theInt : arrayL) System.out.print(theInt + " "); System.out.println(); for (Integer theInt : linkedL) Output is the same, no iterators needed: 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 polymorphism via interfaces

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.toString()); System.out.println(set.subSet(1, 8)); System.out.println(set.tailSet(8)); System.out.println(set.headSet(8)); [2, 7, 8, 9] [2, 7] [8, 9]

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 for (String str : names) System.out.print(str + " "); 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]

Using a Map // over write a value, put returns old value System.out.println(aMap.put("Jessica", new BankAccount("New", 0.99))); Output Jessica $500.00 // put in a new key, get null back System.out.println(aMap.put("NewKey", new BankAccount("NewValue", 0))); null // successful remove return the removed value System.out.println(aMap.remove("Jessica")); New $0.99