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

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

Java Programming: Advanced Topics 1 Collections and Utilities.
Concrete collections in Java library
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.
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.
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.
© 2006 Pearson Addison-Wesley. All rights reserved16-1 Methods in the List Interface (Part 1 of 16)
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.
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
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-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities Chapter 4.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
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.
(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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
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
Computer Science 209 Software Development Java Collections.
תוכנה 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.
Data structures and algorithms in the collection framework 1.
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.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
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.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
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.
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.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
©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.
Java Collections OOP tirgul No
Chapter 19 Java Data Structures
Software Development Java Collections
University of Central Florida COP 3330 Object Oriented Programming
Lecture 6: Collections.
Java语言程序设计 马 皓
Collections Framework
CSE 1020: The Collection Framework
Introduction to Collections
Presentation transcript:

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

Java Collection Transparency No. 2 The Java Collection API Interfaces: Collection Set SortedSet, List Map SortedMap Iterator ListIterator Comparator

Java Collection Transparency No. 3 Summary of all interfaces in the java Collection API Collection Interfaces : The primary means by which collections are manipulated. Collection Set, List A group of objects. May or may not be ordered; May or may not contain duplicates. Set SortedSet The familiar set abstraction. No duplicates; May or may not be ordered. SortedSet elements automatically sorted, either in their natural ordering (see the Comparable interface), or by a Comparator object provided when a SortedSet instance is created. List Ordered collection, also known as a sequence. Duplicates permitted; Allows positional access.

Java Collection Transparency No. 4 Map SortedMap A mapping from keys to values. Each key can map to at most one value (function). SortedMap A map whose mappings are automatically sorted by key, either in the keys' natural ordering or by a comparator provided when a SortedMap instance is created.

Java Collection Transparency No. 5 classes of the java collection API 1.AbstractCollection (Collection) AbstractSet (Set) HashSet, TreeSet(SortedSet) AbstractList (List) ArrayList, AbstractSequentialList LinkedList AbstractMap (Map) HashMap TreeMap (SortedMap) WeakHashMap Arrays Collections

Java Collection Transparency No. 6 General-Purpose Implementation classes The primary implementations of the collection interfaces. HashSet : Hash table implementation of the Set interface. TreeSet : Red-black tree implementation of the SortedSet interface. ArrayList : Resizable-array implementation of the List interface. (Essentially an unsynchronized Vector.) The best all-around implementation of the List interface. LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques). HashMap : Hash table implementation of the Map interface. (Essentially an unsynchronized Hashtable that supports null keys and values.) The best all-around implementation of the Map interface. TreeMap : Red-black tree implementation of the SortedMap interface.

Java Collection Transparency No. 7 The java.util.Collection interface represents a group of objects, known as its elements. no direct implementation The primary use : pass around collections of objects where maximum generality is desired. Ex: List l = new ArrayList( c ) ; // c is a Collection object

Java Collection Transparency No. 8 The definition public interface Collection { // Basic properties int size(); boolean isEmpty(); boolean contains(Object element); // use equals() for comparison boolean equal(Object); int hashCode(); // new equals() requires new hashCode() // basic operations boolean add(Object); // Optional; return true if this changed boolean remove(Object); // Optional; use equals() (not ==)

Java Collection Transparency No. 9 Why using Iterators instead of Enumerations Iterator allows the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. public interface Iterator { boolean hasNext(); // cf: hasMoreElements() Object next(); // cf: nextElement() void remove(); // Optional } // a simple Collection filter using iterator that Enumeration could not help static void filter(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) { if ( no-good( i.next() ) ) i.remove(); // i.next() is removed from c i.remove(); // exception raised, cannot remove more than once ! } }

Java Collection Transparency No. 10 The Set Interface is a Collection that cannot contain duplicate elements. models the mathematical set abstraction. contains no methods other than those inherited from Collection. same signatures but different semantics ( meaning ) Collection c = new LinkedList(); Set s = new HashSet(); String o = a; c.add(o); c.add(o) ; // both return true; c.size() == 2 s.add(o); s.add(o) ; // 2nd add() returns false; s.size() == 1 It adds the restriction that duplicate elements are prohibited. Collection noDups = new HashSet(c); // a simple way to eliminate duplicate from c Two Set objects are equal if they contain the same elements. Two direct implementations: HashSet TreeSet

Java Collection Transparency No. 11 Basic Operations A simple program to detect duplicates using set: import java.util.*; public class FindDups { public static void main(String args[]) { Set s = new HashSet(); // or new TreeSet(), another implementation of Set // following code uses Set methods only for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate detected: + args[i]); System.out.println(s.size()+" distinct words detected: "+s); } } % java FindDups i came i saw i left Duplicate detected: i 4 distinct words detected: [came, left, saw, i]

Java Collection Transparency No. 12 The Map Interface A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Three implementations: HashMap, which stores its entries in a hash table, is the best- performing implementation. TreeMap, which stores its entries in a red-black tree, guarantees the order of iteration. Hashtable has also been retrofitted to implement Map. All implementation must provide two constructors: (like Collections) Assume M is your implementation M() // empty map M(Map m) // a copy of map from m

Java Collection Transparency No. 13 The Map interface public interface Map { // Map does not extend Collection // Basic Operations // put or replace, return replace object // NOTE: different from Weisss insert(Hashable x) Object put(Object key, Object value); // optional Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty();

Java Collection Transparency No. 14 The Map interface // Bulk Operations void putAll(Map t); //optional void clear(); // optional // Collection Views; // backed by the Map, change on either will be reflected on the other. public Set keySet(); // cannot duplicate by definition!! public Collection values(); // can duplicate public Set entrySet(); // no equivalent in Dictionary // nested Interface for entrySet elements public interface Entry { Object getKey(); Object getValue(); Object setValue(Object value); } }

Java Collection Transparency No. 15 Basic Operations a simple program to generate a frequency table import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i=0; i<args.length; i++) { Integer freq = (Integer) m.get(args[i]); // key is a string m.put(args[i], (freq==null ? ONE : new Integer( freq.intValue() + 1))); } // value is Integer System.out.println( m.size()+" distinct words detected:"); System.out.println(m); } } > java Freq if it is to be it is up to me to delegate 8 distinct words detected: {to=3, me=1, delegate=1, it=2, is=2, if=1, be=1, up=1}

Java Collection Transparency No. 16 Collection Views methods allow a Map to be viewed as a Collection in three ways: keySet: the Set of keys contained in the Map. values: The Collection of values contained in the Map. This Collection is not a Set, as multiple keys can map to the same value. entrySet: The Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry that is the type of the elements in this Set. the standard idiom for iterating over the keys in a Map: for (Iterator i = m.keySet().iterator(); i.hasNext(); ) { System.out.println(i.next()); if(no-good(…)) i.remove() ; } // support removal from the back Map Iterating over key-value pairs for (Iterator i=m.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry) i.next(); System.out.println(e.getKey() + ": " + e.getValue()); }

Java Collection Transparency No. 17 Actual Collection and Map Implementations Implementations are the actual data objects used to store collections (and Maps). Three kinds of implementations: General-purpose Implementations the public classes that provide the primary implementations of the core interfaces. Wrapper Implementations used in combination with other implementations (often the general- purpose implementations) to provide added functionality. Convenience Implementations Convenience implementations are mini-implementations, typically made available via static factory methods that provide convenient, efficient alternatives to the general-purpose implementations for special collections (like singleton sets).

Java Collection Transparency No. 18 General Purpose Implementations Hash Table Resizable array balanced tree linked list SetHashSet TreeSet (sortedSet) List ArrayList Vector LinkedList Map HashMap Hashtable TreeMap (sortedMap)

Java Collection Transparency No. 19 Properties of the implementations consistent names as well as consistent behavior. full implementations [of all the optional operations]. All permit null elements, keys and values. unsynchronized. remedy the deficiency of Hashtable and Vector can become synchronized through the synchronization wrappers All have fail-fast iterators, which detect illegal concurrent modification during iteration and fail quickly and cleanly. All are Serializable, all support a public clone() method. should be thinking about the interfaces rather than the implementations. The choice of implementation affects only performance.

Java Collection Transparency No. 20 HashSet vs treeSet (and HashMap vs TreeMap) HashSet/ HashMap is much faster (constant time vs. log time for most operations), but offers no ordering guarantees. always use HashSet/HashMap unless you need to use the operations in the SortedSet, or in-order iteration. choose an appropriate initial capacity of your HashSet if iteration performance is important. The default initial capacity is 101, and that's often more than you need. can be specified using the int constructor. Set s= new HashSet(17); // set bucket size to 17

Java Collection Transparency No. 21 The Collections class static int binarySearch(List list, Object key [, Comparator c]) static void copy(List dest, List src) // foreach i d.set(i, s.get(i)); static Enumeration enumeration(Collection c) Returns an enumeration over the specified collection. static void fill(List list, Object o) static Object max(Collection coll [, Comparator comp] ) static Object min(Collection coll [, Comparator comp] ) static List nCopies(int n, Object o) static void reverse(List l) static Set singleton(Object o) static Comparator reverseOrder() // assume a is of type String[] // usage: Arrays.sort(a, Collections.reverseOrder()); static void shuffle(List list [, Random rnd]) static void swap(List, int, int) static void rotate(List, int d) ;// obj at i moved to ( i - d mod size())