Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 

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:
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.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  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.
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.
The Java Collections Package C. DeJong Fall 2001.
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
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.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
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.
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.
(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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections –data structures and Algorithms L. Grewe.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
1 Java Collection: Data structure framework. 2 Background collections store and organize objects for efficient access Java collections: traditional data.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Sadegh Aliakbary Sharif University of Technology Fall 2012.
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.
Set and Map IS 313, Skeletons  Useful coding patterns  Should understand how and why they work how to use  possible quiz material.
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.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Java Collections CHAPTER 3-February-2003
Java Collections OOP tirgul No
Programming & Data Structures
Introduction to Collections
Introduction to Collections
JAVA Collections Framework Set Interfaces & Implementations
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Presentation transcript:

Collections CS3250

Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 

Outline  java.util.Arrays  Comparing objects  Generics  Collections  java.util.Collections  Maps

java.util.Arrays  Binary search  equals  fill  sort  asList  toString

Comparing objects  Comparable – implemented in class of objects being compared  Comparator – implemented in class that is separate from the class of the objects being compared public interface Comparable { public int compareTo(T o); } public interface Comparator { public int compare(T o1, T o2); } "natural ordering"

Generics  New in Java 1.5  Generic programming: write code that can be reused for objects of many different types -- Core Java (7 th ed., p. 707)

Example  The old way:  With generics: List inventory = new LinkedList(); inventory.add("Brass Lantern");... String item = (String) inventory.get(0); List inventory = new LinkedList (); inventory.add("Brass Lantern");... String item = inventory.get(0);

Advantages?  The old way:  With generics: List inventory = new LinkedList(); inventory.add("Brass Lantern");... String item = (String) inventory.get(0); List inventory = new LinkedList (); inventory.add("Brass Lantern");... String item = inventory.get(0);

Advantages  No casts needed  Compiler can check types List inventory = new LinkedList(); inventory.add("Brass Lantern");... String item = (String) inventory.get(0); List inventory = new LinkedList (); inventory.add("Brass Lantern");... String item = inventory.get(0);

Iterators  Used to traverse collections  How can a method be optional when implementations are required for every method in the interface? public interface Iterator { boolean hasNext(); E next(); void remove(); //optional }

Using iterators  Should always call hasNext before calling next  Otherwise could get NoSuchElement exception  Can use "for each" loop with any object that implements Iterable interface Iterator iter = c.iterator(); while (iter.hasNext()) { String element = (String) iter.next(); // Do something with element } for (String element: c) { // Do something with element }

Iterators: C++ vs. Java C++: iterators are modeled after array indexes (pointers)  Can advance position independently of accessing element Java: like reading from a file  Accessing elements and advancing position are inseparable  Iterator is always "between" elements Iterator iter = c.iterator(); while (iter.hasNext()) { String element = iter.next(); // Do something with element } vector ::iterator iter; for (iter = v.begin(); iter != v.end(); iter++) { cout << *iter; // Do more stuff with *iter } Groucho Harpo Chico Groucho Harpo Chico

Collections  Interfaces  Implementations  List  Set  Queue  Map

Separating interfaces and implementations  Specify implementation only when you construct the collection object:  Why is this a good approach? List inventory = new LinkedList (); inventory.add("Brass Lantern);

Interface Hierarchy Collection ListSet SortedSet Queue Map SortedMap

public interface Collection extends Iterable { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator iterator(); // Bulk operations boolean containsAll(Collection c); boolean addAll(Collection c); //optional boolean removeAll(Collection c); //optional boolean retainAll(Collection c); //optional void clear(); //optional // Array operations Object[] toArray(); T[] toArray(T[] a); }

public interface Collection extends Iterable { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator iterator(); // Bulk operations boolean containsAll(Collection c); boolean addAll(Collection c); //optional boolean removeAll(Collection c); //optional boolean retainAll(Collection c); //optional void clear(); //optional // Array operations Object[] toArray(); T[] toArray(T[] a); }

public interface Collection extends Iterable { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator iterator(); // Bulk operations boolean containsAll(Collection c); boolean addAll(Collection c); //optional boolean removeAll(Collection c); //optional boolean retainAll(Collection c); //optional void clear(); //optional // Array operations Object[] toArray(); T[] toArray(T[] a); } For more information about generic wildcards ( ? and ? extends E ) see extra/generics/subtype.html

public interface Collection extends Iterable { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator iterator(); // Bulk operations boolean containsAll(Collection c); boolean addAll(Collection c); //optional boolean removeAll(Collection c); //optional boolean retainAll(Collection c); //optional void clear(); //optional // Array operations Object[] toArray(); T[] toArray(T[] a); }

public interface Collection extends Iterable { // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator iterator(); // Bulk operations boolean containsAll(Collection c); boolean addAll(Collection c); //optional boolean removeAll(Collection c); //optional boolean retainAll(Collection c); //optional void clear(); //optional // Array operations Object[] toArray(); T[] toArray(T[] a); } What do these optional methods have in common?

Implementations InterfaceImplementations Hash tableResizable array TreeLinked listHash table + linked list SetHashSetTreeSetLinkedHashSet ListArrayListLinkedList QueueLinkedList MapHashMapTreeMapLinkedHashMap

List  Ordered Collection  Allows duplicate elements  Provides positional access  Permits arbitray range operations (sublists) pie ice cream cake 0123 System.out.println(list.get(2)); pie

List implementations  LinkedList  Quickly add and remove elements anywhere in the list  Not well-suited for random access ("staggeringly inefficient")  ArrayList  Works well for random access  Takes more time to add and remove elements (except at the end)

List iterators public interface ListIterator extends Iterator { boolean hasNext(); E next(); boolean hasPrevious(); E previous(); int nextIndex(); int previousIndex(); void remove(); //optional void set(E e); //optional void add(E e); //optional } element = iter.next() System.out.println(element); iter.remove(); Groucho Harpo Chico Can move forward or backward Must call next (or previous ) before calling remove. remove deletes the element just accessed. Must call next (or previous ) before calling remove. remove deletes the element just accessed.

Set  Set interface contains only methods from Collection.  Cannot contain duplicate elements.  Two sets are equal if they contain the same elements. (Order is not important.) pie ice cream cake

Set implementations  HashSet – best performance, "chaotic ordering"  LinkedList – substantially slower, orders elements based on values  LinkedHashSet – orders elements based on order of insertion into the set, performance almost as good as HashSet

Set operations  s1.containsAll(s2) – Returns true if s2 is subset of s1  s1.addAll(s2) – Transforms s1 into union of s1 and s2  s1.retainAll(s2) – Transforms s1 into intersection of s1 and s2  s1.removeAll(s2) – Transforms s1 into the set difference of s1 and s2

Queue  "A collection for holding elements prior to processing" (Java Tutorial)  Typically use FIFO ordering, but there are other orderings (e.g., priority queue)  Ordering determines where an element will be added and which element will be deleted. public interface Queue extends Collection { E element(); boolean offer(E e); E peek(); E poll(); E remove(); }

Two forms of queue methods  offer is intended only for use on bounded (fixed size) queues. Returns false if element cannot be added.  remove and poll remove and return the head of the queue, which is determined by the queue's ordering.  poll and peek return null if the queue is empty Throws exceptionReturns special value Insert add(e)offer(e) Remove remove()poll() Examine element()peek()

java.util.Collections  Sorting  merge sort: fast (n log(n)) and stable  Shuffling  "Routine data manipulations"  reverse, fill, copy, swap, addAll  Searching – binarySearch  Composition  frequency, disjoint

Maps  Stores key/value pairs of objects  Duplicate keys are not allowed  Not part of the Collection hierarchy  Returns keys as a Set view  Returns values as a Collection

public interface Map { V put(K key, V value); V get(Object key); V remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); void putAll(Map m); void clear(); public Set keySet(); public Collection values(); public Set > entrySet(); public interface Entry { K getKey(); V getValue(); V setValue(V value); } Basic Operations Bulk Operations Collection Views Interface for entrySet elements

Word Frequency From the Java Tutorial: java Freq if it is to be it is up to me to delegate 8 distinct words: {to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2} import java.util.*; public class Freq { public static void main(String[] args) { Map m = new HashMap (); // Initialize frequency table from command line for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + " distinct words:"); System.out.println(m); }

java Freq if it is to be it is up to me to delegate 8 distinct words: {to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2} java Freq if it is to be it is up to me to delegate 8 distinct words: {be=1, delegate=1, if=1, is=2, it=2, me=1, to=3, up=1} java Freq if it is to be it is up to me to delegate 8 distinct words: {if=1, it=2, is=2, to=3, be=1, up=1, me=1, delegate=1} HashMap TreeMap LinkedMap Map m = new _______ ();

Summary of implementations  The Java Tutorial gives this list of "most commonly used" implementations: SetHashSet ListArrayList MapHashMap QueueLinkedList