Concrete collections in Java library

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

Chapter 22 Implementing lists: linked implementations.
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Introduction to Computation and Problem
Java Programming: Advanced Topics 1 Collections and Utilities.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
Chapter 24 Lists, Stacks, and Queues
ITEC200 Week04 Lists and the Collection Interface.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Double-Linked Lists and Circular Lists
John Hurley Cal State LA
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
The List ADT Textbook Sections
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
CE203 - Application Programming Autumn 2013CE203 Part 41 Part 4.
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.
Collections Chapter Java Collection Frameworks The Java collection framework is a set of utility classes and interfaces. Designed for working with.
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.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
1 Collections Working with More than One Number or Data Type or Object.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Chapter 19 Java Data Structures
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Lists, Stacks, Queues, and Priority.
Java Collections. Collections, Iterators, Algorithms CollectionsIteratorsAlgorithms.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
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.
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.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
The Java Collections Framework Chapters 7.5. Outline Introduction to the Java Collections Framework Iterators Interfaces, Abstract Classes and Classes.
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/20/03A2-1 CS494 Interfaces and Collection in Java.
HIT2037- HIT6037 Software Development in Java 22 – Data Structures and Introduction.
1 Java Collection: Data structure framework. 2 Background collections store and organize objects for efficient access Java collections: traditional data.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
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.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
List Interface and Linked List Mrs. Furman March 25, 2010.
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.
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.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
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.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Java Collections Framework The client view. The Big Picture.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Using the Java Collection Libraries COMP 103 # T2
Objectives After studying this chapter you should understand the following: the role of iterators in container classes; various implementations of the.
Chapter 19 Java Data Structures
Collections Framework
Presentation transcript:

Java Collection framework: On concrete collections and their implementation

Concrete collections in Java library ArrayList: indexed sequence that grows/shrinks dynamically LinkedList: ordered sequence that allows efficient insertions and removal at any location HashSet: unordered collection that rejects duplicates TreeSet: sorted set EnumSet: set of enumerated type values (implements Set) LinkedHashSet: set that remembers the order in which elements were inserted PriorityQueue: allows efficient removal of the smallest element HashMap: stores key/value associations TreeMap: map in which the keys are sorted EnumMap: keys belong to an enumerated type (impl. Map) LinkedHashMap: remembers the order in which added WeakHashMap: keys and entries that can be reclaimed by the garbage collector if the keys are not used elsewhere IdentityHashMap: keys that are compared by ==, not equals

LinkedList: doubly-linked list LinkedList implements the List interface and extends the AbstractCollection class (indirectly through AbstractSequentialList) offers inexpensive operations to add into and remove from the middle of a data structure LinkedList also gives (expensive) implementations for using array indices: get (i), listIterator (i), etc. LinkedList provides methods to get, remove and insert an element at the beginning and end these extra (see API) operations support efficient stack, queue, or double-ended queue (deque) handling; implements the Queue interface

LinkedList: doubly-linked list (cont.)

LinkedList: doubly-linked list (cont.) List <E> list = new LinkedList <E> (aCollection) list.addFirst (obj) list.addLast (obj) obj = list.getFirst () obj = list.getLast () obj = list.removeFirst () obj = list.removeLast () list traversal is done by an implementation of ListIterator a recursive list having itself as an element is not permitted (but not checked)

Removing an element from a linked list

Adding an element to a linked list

ArrayList: sequentially allocated list the class ArrayList implements List internally, contains an Object [ ] array that is automatically reallocated when needed methods to manipulate the array that stores the elements: ensureCapacity (minCapacity), and trimToSize () gives efficient (O(1)) implementations for methods with index positions, such as get (i), set (i, obj), etc. implements the marker interface RandomAccess note that ArrayList does not provide operations for stack and queue handling (not a Queue) element traversals are made by an implementation of ListIterator

Removing an element from an array

Implementation of Java Collections uses object-oriented mechanisms and patterns to organize the services and the classes: encapsulation, inheritance, polymorphism; Template Method, Factory Method, Iterator, Strategy, Proxy, etc. however, data structures are not organized into a single-root class library some libraries handle maps uniformly as collections of pair elements to support code reuse, the framework provides abstract classes, e.g., AbstractCollection AbstractCollection implements Collection, leaving operations, such as iterator () and size (), abstract

Relationships between framework classes

Implementation of Java Collections (cont.) the skeleton class either gives a method some default definition, say, throwing an exception, or implements it in terms of more basic operations e.g., utility routines, such as toString () and addAll (aCollection), can be defined in terms of other operations: public class AbstractCollection <E> implements Collection <E> { . . . public abstract Iterator<E> iterator ();

Implementation of Java Collections (cont.) . . . public boolean add (E obj) { // illegal by default throw new UnsupportedOperationException (); } // a hypothetical implementation: public boolean contains (Object obj) { for (E element : this) // calls iterator () if (element.equals (obj)) return true; return false; } // AbstractCollection <E>

Implementation of Java Collections (cont.) the abstract classes are meant to be used by programmers wanting to extend the framework with new implementations of data structures of course, must implement the missing abstract methods to make default ones to work additionally, an implementation may override a ready-made skeleton method to make it legitimate, or to give it a more efficient implementation for a specific concrete data structure

Error Handling very thorough checks; uses unchecked exceptions denied ops throw UnsupportedOperationException unacceptable type throws ClassCastException element constraint (e.g. range) violation throws IllegalArgumentException an accessed empty collection or exhausted iterator throws NoSuchElementException a null parameter (unless null is accepted as an element) throws NullPointerException invalid element index (< 0 or >= size ()) throws IndexOutOfBoundsException especially, constant views may throw UnsupportedOperationException

Iterator error handling Iterator.remove () removes the last element visited by next () removal depends on the state of the iterator throws UnsupportedOperationException if the remove operation is not supported, and throws IllegalStateException if the next method has not yet been called generally, the behavior of an Iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling the method remove

Iterator error handling (cont.) however, ListIterator.remove is guaranteed to throw IllegalStateException if the list was structurally modified (i.e., remove or add have been called) since the last next or previous ListIterator.add (anObject) throws UnsupportedOperationException if the add method is not supported by this list iterator ClassCastException (IllegalArgumentException) if the class (or some other aspect) of the specified element prevents it from being added to this list note that adding does not depend on the state of the iterator (whether next or previous has been called)

Iterator error handling (cont.) the method set (newElement) replaces the last element returned by last next or previous the update is done "in place", i.e., without structurally modifying the data structure however, the method set () itself throws IllegalStateException if neither next nor previous have been called, or if the list was structurally modified (remove or add have been called) since the last next or previous

Fail-Fast Feature iterators generally support the so-called fail-fast feature this means that if the collection is modified after an iterator is created, in any way except through the iterator's own remove or add methods, an exception is thrown only one iterator may be both reading and changing a list, and multiple readers are allowed if they don't do any structural modifications (so, set (obj) is OK) thus, in case of concurrent modification, the iterator fails quickly, rather than risking arbitrary behaviour at an undetermined time in the future

Fail-Fast Feature (cont.) For example, consider the following code: List<String> list = . . .; ListIterator<String> iter1 = list.listIterator (); ListIterator<String> iter2 = list.listIterator(list.size()); iter1.next (); iter1.remove (); iter2.next (); // throws exception last call throws a ConcurrentModificationException since iter2 detects that the list was modified externally

Fail-Fast Feature: Summary an iterator throws ConcurrentModificationException, if it founds that the data structure has been structurally modified by other iterators or by collection operations simple rule: attach as many reader iterators to a collection as you like; alternatively, you can attach a single iterator that can both read and write modification detection is achieved by a mutation count values per each iterator and the collection object note that here "ConcurrentModificationException" doesn't mean to involve any multithreading