Collections –data structures and Algorithms L. Grewe.

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.
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.
Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
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.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
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.
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.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
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.
Data structures and algorithms in the collection framework 1 Part 2.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
111 © 2002, Cisco Systems, Inc. All rights reserved.
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 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.
Arrays, ArrayLists, and Collections. Rationale Suppose we have a program to compute the average of three numbers. We could write a simple little method.
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:
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.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
©SoftMoore ConsultingSlide 1 Java Collections Framework.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
13 Collections Framework. 2 Contents What is Collection? Collections Framework Collections Hierarchy Collections Implementations Set List Map.
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.
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.
AD Lecture #3 Java Collection Framework 1.
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.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
University of Central Florida COP 3330 Object Oriented Programming
Java Collections Overview
Part of the Collections Framework
Introduction to Java Collection
Presentation transcript:

Collections –data structures and Algorithms L. Grewe

Collections Framework “A collections framework is a unified architecture for representing and manipulating collections.” “A collections framework is a unified architecture for representing and manipulating collections.” Data Structures ---Interfaces & ImplementationsData Structures ---Interfaces & Implementations Algorithms ----through java.util.CollectionsAlgorithms ----through java.util.Collections

First Data Structures….

“Collections” A collection groups multiple elements into a single unit. A collection groups multiple elements into a single unit. VectorVector HashtableHashtable arrayarray

Hierarchy of Interfaces Collection (java.util.Collection) Collection (java.util.Collection) SetSet SortedSet SortedSet ListList QueueQueue Map Map SortedMapSortedMap

Collection “A collection represents a group of objects known as its elements.” “A collection represents a group of objects known as its elements.” Some implementations allow duplicates, some don’t. Some implementations allow duplicates, some don’t. Some implementations automatically sort the elements, some don’t. Some implementations automatically sort the elements, some don’t.

Types of Collections Set Set Cannot contain duplicates.Cannot contain duplicates. SortedSet SortedSet Is a set.Is a set. Maintains elements in sorted order.Maintains elements in sorted order. List List An ordered collection.An ordered collection. Queue Queue A collection with additional insertion, extraction, and inspection operations.A collection with additional insertion, extraction, and inspection operations. Usually FIFO.Usually FIFO.

Collections that aren’t Collections Map Map Maps keys to values.Maps keys to values. Cannot contain duplicate keys.Cannot contain duplicate keys. SortedMap SortedMap Maintains key/value pairs in key order.Maintains key/value pairs in key order.

Set Implementations HashSet HashSet No order guarantee., like “hash table”.No order guarantee., like “hash table”. TreeSet TreeSet Value ordered.Value ordered. LinkedHashSet LinkedHashSet Ordered oldest to newest, in terms of insertion.Ordered oldest to newest, in terms of insertion. no duplicate elements are allowed in a Set

List Implementations ArrayList ArrayList Most common.Most common. LinkedList LinkedList Use if insertions are often done at the head.Use if insertions are often done at the head. Positional access: add elements at specific positions add elements at specific positions add and addAll without a position add to the end of the List add and addAll without a position add to the end of the List set and remove return the element overwritten or removed set and remove return the element overwritten or removed Search: return the position of elements Search: return the position of elements Extended Iteration: extended Iterator interface Extended Iteration: extended Iterator interface Range-view: Range-view: return a sublist return a sublist if the sublist is modified, the original List is as well if the sublist is modified, the original List is as well

Map Implementations Hashtable Hashtable No order guaranteeNo order guarantee Constant time get, putConstant time get, put no nullsno nulls HashMap HashMap Like Hashtable but allows nullsLike Hashtable but allows nulls TreeMap TreeMap Key order iteration.Key order iteration. LinkedHashMap LinkedHashMap Insertion order iteration.Insertion order iteration.

Features of Maps Copying via constructor: Copying via constructor: //m is another Map Map copy = new HashMap (m); Check if 2 maps have same entries, Check if 2 maps have same entries, if (m1.entrySet().containsAll(m2.entrySet())) {...} Check if two maps have the same keys: Check if two maps have the same keys: if (m1.keySet().equals(m2.keySet())) {...}

Queue Implementations LinkedList LinkedList Allows for a FIFO queue.Allows for a FIFO queue. PriorityQueue PriorityQueue Iteration based on a value specified at element insertion.Iteration based on a value specified at element insertion. Has the property that only the highest- priority element can be accessed at any time.Has the property that only the highest- priority element can be accessed at any time.

About Sorted Collection Classes Sort by? ObjectNatural Ordering Byte, Integer, Long, Short, Float, Double, BigInteger, BigDecimalSigned Numerical CharacterUnsigned Numerical BooleanBoolean.FALSE < Boolean.TRUE File System Dependent Alphabetical by Path StringAlphabetical DateChronological CollationKeyLocale-Specific Alphabetical For o1.compareTo(o2) : returns negative if o1 < o2 returns 0 if o1 == o2 returns positive if o2 > o2

SortedSet Differences from Set: Differences from Set: Iterator traverses the SortedSet in order Iterator traverses the SortedSet in order toArray returns an in order array of the elements toArray returns an in order array of the elements toString returns a String of the contents in order toString returns a String of the contents in order Implementations: ConcurrentSkipListSet, TreeSet ConcurrentSkipListSet TreeSetConcurrentSkipListSet TreeSet

SortedMap Differences from Map: Differences from Map: Iterator traverses the collection views of a SortedMap in order Iterator traverses the collection views of a SortedMap in order toArray returns an in order array of the keys, values or entries toArray returns an in order array of the keys, values or entries toString returns a String of the contents in order toString returns a String of the contents in order Implementations: ConcurrentSkipListMap, TreeMap ConcurrentSkipListMap TreeMapConcurrentSkipListMap TreeMap

Now a few common data structures….

LinkedList Constant insertion and removal at first/last Constant insertion and removal at first/last Constant insertion and removal at an Iterator Constant insertion and removal at an Iterator Lookup is slow (linear time) Lookup is slow (linear time) Traversal is fast (constant time to find the next element) Traversal is fast (constant time to find the next element) Ordered by insertion Ordered by insertion

Trees Logarithmic insertion and lookup Logarithmic insertion and lookup Sorted order Sorted order Classes: TreeSet, TreeMap Classes: TreeSet, TreeMap

Review of some implemented common data structures InterfacesImplementations Hash Table Resizable Array TreeLinked List Hash Table + Linked List SetHashSetTreeSet LinkedHash Set ListArrayListLinkedList Queue MapHashMapTreeMap LinkedHash Map

Traversing through Collections….

Iterate through Collections for-each for-each If modification of the Collection won’t be done, use the for-each.If modification of the Collection won’t be done, use the for-each. for (Object o : collection){ System.out.println(o);} Iterator Iterator If modifications are to be done, or the for- each doesn’t excite you, use the Iterator.If modifications are to be done, or the for- each doesn’t excite you, use the Iterator.

Iterator “Enables you to traverse through a collection and to remove elements from the collection selectively, if desired.” “Enables you to traverse through a collection and to remove elements from the collection selectively, if desired.” Use the iterator() method on the Collection to get the Collection’s Iterator. Use the iterator() method on the Collection to get the Collection’s Iterator. Methods: Methods: boolean hasNext()boolean hasNext() Object next()Object next() void remove()void remove() Example Example Vector vec = new Vector; // Populate it... Then later, iterate over its elements….. Iterator it = vec.iterator (); while (it.hasNext ()) { Object o = it.next (); //or whatever the class type is } Vector vec = new Vector; // Populate it... Then later, iterate over its elements….. Iterator it = vec.iterator (); while (it.hasNext ()) { Object o = it.next (); //or whatever the class type is }

Another example – no casting ArrayList alist = new ArrayList (); //... Add Strings to alist ………not showing this //... Add Strings to alist ………not showing this //now cycle through and visit each element in ArrayList for (Iterator it = alist.iterator(); it.hasNext(); ) { String s = it.next(); //no casting done here System.out.println(s); } System.out.println(s); }

Example again – with for ArrayList alist = new ArrayList (); //... Add Strings to alist ……… //... Add Strings to alist ……… for (String s : alist) { System.out.println(s); } { System.out.println(s); }

Example again –older style with casting ArrayList alist = new ArrayList (); //... Add Strings to alist ……… //... Add Strings to alist ……… for (Iterator it = alist.iterator(); it.hasNext(); ) { String s = (String)it.next(); // Downcasting is required pre Java 5. { String s = (String)it.next(); // Downcasting is required pre Java 5. System.out.println(s); } System.out.println(s); }

ListIterator Besides the basic Iterator class, ListIterator is implemented by the classes that implement the List interface (ArrayList, LinkedList, and Vector) Besides the basic Iterator class, ListIterator is implemented by the classes that implement the List interface (ArrayList, LinkedList, and Vector) Some methods: Some methods: int nextIndex() Returns the index of the element that would be returned by a subsequent call to next(). int nextIndex() Returns the index of the element that would be returned by a subsequent call to next().nextIndexnext()nextIndexnext() int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous(). int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous().previousIndexprevious()previousIndexprevious()

Converting Collection to Arrays Some Collections allow you to convert to an Array Some Collections allow you to convert to an Array //c is a Collection of Objects Object[] a = c.toArray(); //c is a collection of Strings //we pass an empty string so the compiler knows the correct result type String[] a = c.toArray(new String[0]);

Now for ALGORITHMS

java.util.Collections --- HOW to get some predefined useful ALGORITHMS ---static method HOW to get some predefined useful ALGORITHMS ---static method

ALGORITHMS java.util.Collections methods The collections class has the following methods (static)..see API for complete list: The collections class has the following methods (static)..see API for complete list: sort(List list) - sort the listsort(List list) - sort the list binarySearch(List list, T key) –binary search for keybinarySearch(List list, T key) –binary search for key reverse(List list) - reverse the listreverse(List list) - reverse the list fill(List list, E value) - overwrite every value in list with valuefill(List list, E value) - overwrite every value in list with value copy(List src, List dest) - copy all the elements from src into destcopy(List src, List dest) - copy all the elements from src into dest swap(List list, int i, int j) - swap the elements at the ith and jth position in listswap(List list, int i, int j) - swap the elements at the ith and jth position in list addAll(Collection c, T... elements) - add all the specified elements to c:addAll(Collection c, T... elements) - add all the specified elements to c:

MORE ALGORITHMS java.util.Collections methods frequency(Collection c, Object o) - how many times does o appear in cfrequency(Collection c, Object o) - how many times does o appear in c disjoint(Collection c1, Collection c2) - returns true if c1 and c2 share no elementsdisjoint(Collection c1, Collection c2) - returns true if c1 and c2 share no elements min(Collection coll) – returns min (see API for overloaded min)min(Collection coll) – returns min (see API for overloaded min) max(Collection coll) – returns max (see API for voverloaded max)max(Collection coll) – returns max (see API for voverloaded max)

Algorithms—example Sort import java.util.*; public class Sort { public static void main(String[] args) { public static void main(String[] args) { List list = Arrays.asList(args); List list = Arrays.asList(args); //sort using the elements comparator //sort using the elements comparator Collections.sort(list); Collections.sort(list); System.out.println(list); System.out.println(list); //sort using your own comparator //sort using your own comparator Collections.sort(list, new MyComparator()); Collections.sort(list, new MyComparator()); System.out.println(list); System.out.println(list); }}

Algorithms- binarysearch example int pos = Collections.binarySearch(list, key); //if key isn’t in the list, add it in sorted order if (pos < 0) list.add(-pos-1), key); look up API to see why I add at -pos-1 position..hint if key is not found then binarySearch returns= (-(insertion point) - 1) Suppose pos= -4 that means insertion_point=3 Suppose pos= -4 that means insertion_point=3 So –pos -1 = -(-4) -1 = 4-1 =3 So –pos -1 = -(-4) -1 = 4-1 =3