1 Java Collection: Data structure framework. 2 Background collections store and organize objects for efficient access Java collections: traditional data.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Java Programming: Advanced Topics 1 Collections and Utilities.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
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.
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 
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
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)
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.
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.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
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.
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.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
CS2110: SW Development Methods
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities Chapter 4.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
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.
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.
(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.
Data structures and algorithms in the collection framework 1 Part 2.
1 Concrete collections II. 2 HashSet hash codes are used to organize elements in the collections, calculated from the state of an object –hash codes are.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Chapter 18 Java Collections Framework
LinkedList Many slides from Horstmann modified by Dr V.
תוכנה 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.
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.
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.
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.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1/20/05A-1 © 2001 T. Horton CS 494 Adv. SW Design and Development A Tasting…. Course 1: Design patterns: Intro, example Course 2: Inheritance, Interfaces,
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
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.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Chapter 19 Java Data Structures
Part of the Collections Framework
Introduction to Java Collection
Presentation transcript:

1 Java Collection: Data structure framework

2 Background collections store and organize objects for efficient access Java collections: traditional data structures implemented as an object-oriented framework –currently only "basic data structures sufficient for most needs" –sets, linked lists, arrays, and maps efficiency depends on organization and use –linked vs. sequential allocation, and hashing vs. sorted search trees

3 Interfaces of the collections framework

4 Collection architecture the collections library utilizes heavily inheritance and polymorphism the library is implemented as a kind of (lightweight) framework, and it enables user-defined extensions separation of interfaces + their implementations: –Collection List implemented by ArrayList and LinkedList Set implemented by HashSet and LinkedHashSet –SortedSet implemented by TreeSet

5 Collection architecture (cont.) Map implemented by HashMap, IdentityHashMap, and LinkedHashMap –SortedMap implemented by TreeMap we have Iterable, Iterator and ListIterator interfaces –Iterable: provides the method iterator () –Iterator: hasNext (), next (), and remove () –ListIterator: add (), set (), hasPrevious (), previous (), nextIndex (), etc.. additionally, a set of abstract classes that provide skeletons for implementations –apply the Template Method pattern

6 Generic utility methods you can write utility methods that can operate on any kind of collection public static boolean contains (Collection c, Object obj) { for (E e : c) if (e.equals (obj) ) return true; return false; } the above for statement is a short-hand notation for..for (it = c.iterator (); it.hasNext (); ) { e = it.next ();..

7 Using object-oriented collections the idea: always use collections through interfaces, and separately create them as concrete collections: Set set = new HashSet (); set.add ("first"); set.add ("second"); int n = set.size (); // n is 2 assert set.contains ("first"); you should always ask what is the most general class or interface that can do the required job

8 Design of Collection framework a built-in class library should satisfy many mutually conflicting requirements: –easy to learn and convenient to use –as general as possible: dynamic / flexible / immutable, etc. structures –idiot-proof with complete run-time checks, and –as efficient as hand-coded algorithms fit some language limitations: –Java cannot express and enforce constness at compile time –Java generics involves no run-time type info

9 Design of framework (cont.) the concrete implementations provide different performance and errors the interfaces abstract these differences away providing very general and concise interfaces the design makes compromises between practical requirements and pure conceptual modelling –for example, interfaces have so-called optional operations, forbidden by specific implementations, e.g., Iterator.remove () –a called forbidden optional operation throws UnsupportedOperationException (unchecked) –thus, constant views on collections are supported (only) by run-time checks

10 Design of framework (cont.) such refusal of inherited operations is clearly an is-a violation, at the conceptual level –the general object-oriented substitution principle: "operation that expects an instance of a supertype must also accept an instance of a subtype" does not hold here such solutions are strongly discouraged by most object-oriented methodologies –you should (generally) avoid applying these techniques in the design and interfaces of your own object-oriented applications

11 Overview: Collection expressed as hierarchically organized interfaces Collection represents a "bag" (multiset) of values: duplicates are (in principle) allowed –List is a sequentially ordered set of values –values in a List are ordered by position and can be identified by integer indices (0..) implemented as an array or as a linked list –Set provides otherwise identical interface to Collection but allows no duplicates –values in a Set are not necessarily ordered or sorted SortedSet is sorted by comparison of element values

12 Overview: Map Map is an "associative table" of key-value pairs insert key-value pair: V oldValue = map.put (keyObject, newValue) get value, or null if the key is not found: value = map.get (keyObject) For example, Map map = new HashMap (); map.put ("first", x); map.put ("second", y); map.put ("third", x); assert map.get ("first").equals (x); V v = map.remove ("first");

13 Overview: SortedMap SortedMap is sorted by comparison of element values –either by natural order given by the object class, or by a separate comparison method must either implement the Comparable interface, or use a Comparator object

14 Views into collections in the Java data structure library, Maps are not considered to be Collections however, views use Collection interfaces aMap.entrySet () returns a Set of Map.Entries –Map.Entry provides methods: getKey (), getValue (), and setValue (v) –however, no getEntry (key) is provided (vs. C++ STL) - Entry is an interface, only note that collection views are an application of the Proxy design pattern [Gamma et al, p. 207]

15 Views into collections (cont.) collection methods are not by default thread-safe, i.e., not synchronized for concurrent access –this avoids unnecessary overheads interfaces do not determine whether implemented methods are synchronized or not (as usual) thread-safe collection handling is supported by separate synchronized views, created by a call: Collections.synchronizedX (X c), where X can be Collection, List, Map, Set, SortedMap, or SortedSet note: class Collections is not interface Collection

16 Views into collections (cont.) similarly, a constant collection may be created by a call: –Collections.unmodifiableX (X c) framework also offers "generic" (C++ STL like) algorithms: searching and sorting, etc. the old "legacy" classes (Vector, Hashtable, etc.) have been fitted into the framework –however, the legacy classes are synchronized, and thus involve a substantial overhead

17 Collections and iterators all Collection objects and their iterators show similar general behaviour: // implementation-dependency here only: Collection coll = new LinkedList (); // use through abstract interface: coll.add (element);... Iterator iterator = coll.iterator (); while (iterator.hasNext ()) { E element = iter.next (); //.. do something with element }...

18 Using iterators the method iterator () returns an implementation of Iterator that can be used to traverse and possibly modify the collection: while (iter.hasNext ())... obj = iter.next () obj = iter.remove () of course, accessing past the already reached end of a list is considered a programming error –if hasNext () returns false, then calling next () will throw (unchecked) NoSuchElementException

19 Advancing an iterator

20 Using iterators (cont.) iterator represents a position between two elements in the data structure –note: C++ containers use a different strategy: iterators are (abstract) pointers to elements an iterator can provide a way to remove an element related to that position –iterator.remove () removes the element returned by the last next () –note that next () must be called (at least once) before each removal

21 Collection services a sample of Collection methods: Iterator iterator () int size (); boolean isEmpty () boolean contains (Object v) boolean containsAll (Collection c) boolean equals (Object other) boolean add (E element) boolean addAll (Collection c) boolean remove (Object element)

22 Collection services (cont.)... boolean removeAll (Collection c) void clear () boolean retainAll (Collection c) Object [ ] toArray () T [ ] toArray(T [ ] a) // may allocate bigger note that E [ ] array =... List list = Arrays.asList (array) // a proxy can be used to create a fixed-size list backed by the specified array (changes "write through" to the array)

23 Collection services (cont.) many operations (add, etc.) return a boolean value to indicate whether the operation really modified the data structure –e.g., remove (obj) returns true if a maching (equals) object was removed –note that iterator's remove returns void (as does ListIterator) for a more detailed description of java.util.Collection services, see the API or the textbook, pp

24 The List Interface the List interface defines a sequentially ordered set of values: // pos means position index 0..size list.add (pos, obj) list.addAll (pos, aCollection) list.get (pos) list.set (pos, obj) obj = list.remove (pos) ListIterator iter = list.listIterator () ListIterator iter = list.listIterator (fromPos)

25 The List Interface... pos = list.indexOf (obj) pos = list.lastIndexOf (obj) sublist = list.subList (from, beyond) // get view subList creates a proxy object that –is backed by this list, so non-structural changes are reflected in the original list, and vice-versa –supports all of the optional list operations supported by the backing list –becomes undefined if the backing list is structurally modified in other way than via the proxy

26 ListIterator the related ListIterator traverses the elements in order, possibly also modifying the data structure iter = list.listIterator (fromPos); backwards traversing, index handling, and insertion of values: while (iter.hasPrevious ())... obj = iter.previous () iter.add (obj) iter.set (obj) pos = iter.nextIndex () pos = iter.previousIndex ()

27 ListIterator (cont.) ListIterator represents an indexed position within a sequential data structure –the iterator represents a position between two elements; or at beginning before all others (0); or at end, after all elements (size ()) the method add (v) inserts the new element at the current position, i.e., before the next element –if previous () is called after add, the new element is returned –so, calling add repeatedly puts elements in the exact order they are given –increases by one nextIndex and previousIndex note that the Iterator interface allowed only a removal of an element (optional)