Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

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 CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
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.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
12-Jul-15 Lists in Java Part of the Collections Framework.
1 Frameworks Part 2. 2 Collections Framework Java API contains library of useful data structures Collections library also serves as framework for adding.
The Java Collections Package C. DeJong Fall 2001.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
CS2110: SW Development Methods
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.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Lists and the Collection Interface Review inheritance & collections.
LinkedList Many slides from Horstmann modified by Dr V.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
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.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Java 2 Collections Bartosz Walter Software Engineering II.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
1 TCSS 342, Winter 2005 Lecture Notes Linked List Implementation Weiss Ch. 6, pp Weiss Ch. 17, pp
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Java Programming: From the Ground Up Chapter 17 The Java Collections Framework.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
List data type(ADT). Lists Elements : a 1,a 2,a 3,… a i-1,a i, a i+1,…a n Null List contains: 0 elements Types of Operations on list 1.Insertion 2.Deletion.
Introduction to Computational Modeling of Social Systems Prof. Lars-Erik Cederman Center for Comparative and International Studies (CIS) Seilergraben 49,
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,
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.
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
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
CS 151: Object-Oriented Design December 3 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Chapter 5: The List Abstract Data Type
Programming & Data Structures
Data Structures Lakshmish Ramaswamy.
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
Introduction to Collections
Introduction to Collections
Introduction to Collections
Collections Framework
Introduction to Collections
Part of the Collections Framework
Java Generics & Iterators
Presentation transcript:

Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection Interface The List Interface The Iterator Interface The ListIterator Interface

Unit 292 The Java Collections Framework A collection is a group of objects. The Java Collections Framework (JCF) is a set of important utility classes and interfaces in the java.util package for working with collections. The Java Collections Framework consists of three parts: –Interfaces: the abstract data types that the framework supports. E.g., java.util.Comparator, java.util.Collection, java.util.Iterator –Implementations: concrete versions of these interfaces. E.g., java.util.ArrayList and java.util.LinkedList. –Algorithms: predefined actions defined on the interfaces or their implementations. E..g., Collections.sort(), Collections.binarySearch()

Unit 293 Why Develop the JCF? An array is a common data structure suitable in many situations However, arrays are not always good for some of the following: –They require size information for creation –Inserting an element in the middle of an array leads to moving other elements around –Deleting an element from the middle of an array leads to moving other elements around Other data structures, like linked list and trees, are better for some situations The JCF provides efficient implementations for these common data structures By using the JCF interfaces, these data structures can be manipulated in a uniform way

Unit 294 Some Benefits of using the JCF Benefits –Reduces programming effort: by providing useful data structures, the programmer can focus on the problem at hand. –Improves program speed and quality: by providing high- performance, high-quality implementations for the most common data structures –Allows interoperability among unrelated APIs –Fosters software reuse Concerns –JCF data structures work only with objects, not primitive types. If we deal with primitive types, we use Wrapper classes. –A Collection can contain incompatible types at the same time –JFC methods are generic; must always downcast from Object to our types

Unit 295 Collections Framework’s Interfaces Object > Comparable CollectionsAbstractCollection AbstractList AbstractSequentialList LinkedList ArrayList > Collection > Comparator > Iterator > List > ListIterator java.lang

Unit 296 Root of the collection hierarchy Represents a group of objects, known as its elements. Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. Defines all of the operations that are common to most if not all kinds of collections Some collection operations are optional – meaning that some implementations may not support them. In practice such methods would throw a runtime UnsupportedOperationException The Collection interface

Unit 297 The Collection Interface // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); // Optional // Array Operations Object[] toArray(); Object[] toArray(Object a[]); // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); // Optional // Array Operations Object[] toArray(); Object[] toArray(Object a[]); Three types of operations

Unit 298 The List Interface The List interface represents an ordered collection of objects. Each element in a list has an index, or position. The indexes range from 0 to size() – 1. List extends Collection. It has the following additional methods to those it inherits and overrides: public abstract void add(int index, Object object); public abstract Object get(int index); public abstract int indexOf(Object object); public abstract int lastIndexOf(Object object); public abstract Object remove(int index); public abstract Object set(int index, Object object); public abstract ListIterator listIterator(); public abstract ListIterator listIterator(int index); public abstract List subList(int fromIndex, int toIndex);

Unit 299 The Iterator Interface public interface Iterator{ public abstract boolean hasNext(); public abstract Object next(); public abstract void remove(); } Iterators provide a way of visiting the elements of a collection one by one For arrays, the loop index represents the iterator. for (int i=0; i < 10; i++) {... } Think of an iterator as a cursor that resides between elements of the collection To visit all the elements of a collection object c, a code such as the following may be used: Iterator iter = c.iterator(); while(iter.hasNext( )){ Object obj = iter.next(); process(obj); }

Unit 2910 The Iterator Interface (continued) Object next() Moves the iterator forward one position and returns the element it has passed over void remove() The remove() method of an iterator removes the element whose reference was returned by the last call to next(). boolean hasNext() Returns true if the iterator can be moved forward hasNext() false hasNext() true next() iterator

Unit 2911 The Iterator Interface (cont’d) Iterator iter = c.iterator( ); iter.next();// skip over the first element iter.remove();// remove the first element The following code removes the first element in a collection c: Iterator iter = c.iterator(); or iter.remove();// illegal It is illegal to call the remove() method of an iterator if it was not preceded by a call to next(). For example, the following is invalid. Each remove call has to be preceded by a call to next(). Executing such program fragments will lead to run time exception IllegalStateException Iterator iter = c.iterator(); iter.next(); iter.remove(); iter.remove(); // illegal

Unit 2912 Example 1: The Iterator Interface 1 import java.util.*; 2 public class TestIterator { 3 public static void main(String[] args) { 4 //LinkedList list = new LinkedList(); // making arraylist or linkedlist is different at this 5 ArrayList list = new ArrayList(); // level. The remaining statements are the same 6 for(int i = 0; i < 6; i++) 7 list.add(new Integer(i)); // add method of list object 8 Iterator iter = list.iterator(); 9 // find the sum of the ineteger values stored in list 10 int sum=0; 11 while (iter.hasNext()){ 12 Object item = iter.next(); // Next item as an Object. 13 Integer num = (Integer)item; // Type-cast item to an Integer. 14 sum = sum + num.intValue(); // Add the number to the sum 15 } 16 System.out.println(list); 17 System.out.println(“sum = “+sum); 18 } 19 }

Unit 2913 The ListIterator Interface public abstract boolean hasPrevious(); public abstract int nextIndex(); public abstract Object previous(); public abstract int previousIndex(); public abstract add(Object object); public abstract void set(Object object); The ListIterator interface extends Iterator to allow bi-directional traversal of a list, and the modification of a list. It has the following additional methods to those it inherits and overrides: -listIterator() or listIterator(int pos) are the methods that return an instance of listIterator. listIterator() returns an iterator at position 0, but listIterator(int pos) returns An iterator that starts at position pos. -ListIterator supports reverse traversal via previous and hasPrevious -In ListIterator, the cursor sits between the element that would be returned by a call to next() and the element that would be returned by a call to previous()

Unit 2914 The ListIterator interface (continued) setOverwrites last element returned by next() or previous(). NB: set must be preceded by a call to next() or previous() addAdds immediately before the current cursor position (ie in between elements that would be returned by previous() and next()) removeRemoves last element returned by next() or previous(). NB: remove must be preceded by a call to next() or previous() A description and some conditions for set, add, and remove methods

Unit 2915 Example 2: The ListIterator Interface 1 import java.util.*; 2 public class TestListIterator { 3 public static void main(String[] args) { 4 //LinkedList list = new LinkedList(); 5 ArrayList list = new ArrayList(); 6 7 ListIterator iter2, iter1 = list.listIterator(); 8 9 for(int i = 0; i < 6; i++) 10 iter1.add(new Integer(i)); // add method of list iterator iter2 = list.listIterator(list.size()); // places iterator at the end 13 iter2.previous(); // jumps over the last element in reverse order 14 iter2.add(new Integer(25)); // add immediately before the last element 15 iter2.previous(); 16 iter2.remove(); 16 System.out.println(list); 17 } 18 }

Unit 2916 Checking Iterators The ability of iterators to modify a collection can cause problems if there are several iterators attached to one collection. Assume that list has many objects. The last statement of this code fragment generates an exception ListIterator iter1 = list.listIterator(); ListIterator iter2 = list.listIterator(); // two iterators for the same list iter1.next(); iter1.remove(); iter2.next(); // throws ConcurrentModificationException Follow this rule: –You can have many read-only iterators, attached to a collection. –You can have just one read/write iterator atteched to a collection.

Unit 2917 Example 3: The ListIterator Interface 1 import java.util.*; 2 public class TestListIterator2 { 3 public static void main(String[] args) { 4 ArrayList list = new ArrayList(); 5 int bonus = 1; 6 7 for(int i = 0; i < 6; i++) 8 list.add(new Integer(i)); // add method of the list 9 10 ListIterator iter = list.listIterator(); System.out.println("List before: " + list); while (iter.hasNext()){ 15 Integer myInt = (Integer)iter.next(); 16iter.set(new Integer(myInt.intValue()+bonus)); // replacing the object returned by 17 // next() by the one between brackets of set method) 18 } 19 System.out.println("List after : " + list); 20 } 21 }