Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Computer Science 112 Fundamentals of Programming II List Iterators.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L16 (Chapter 22) Java Collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
© 2006 Pearson Addison-Wesley. All rights reserved16-1 Methods in the List Interface (Part 1 of 16)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
12-Jul-15 Lists in Java Part of the Collections Framework.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create 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
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Lists, Stacks, Queues, and Priority.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
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.
(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.
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
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.
Chapter 18 Java Collections Framework
LinkedList Many slides from Horstmann modified by Dr V.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
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: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
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.
Chapter 19 Java Data Structures
Introduction to Collections
Introduction to Collections
Chapter 20 Lists, Stacks, Queues, and Priority Queues
Introduction to Collections
Introduction to Collections
Collections Framework
Introduction to Collections
Presentation transcript:

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Chapter 18: Collections With formatting and other updates by Dr. L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2 Chapter Topics Introduction to the Java Collections Framework Lists Sets Maps The Collections Class Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to the Java Collections Framework Collection -- an object which can store other objects Collection elements -- objects in a collection Collections provide methods for adding and removing elements, for searching for a particular element within the collection.etc. Java Collections Framework (JCF) -- a library of classes and interfaces for working with collections of objects Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4 The Main Types of Collections Lists – covered in good detail Sets – not covered Maps – not covered Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5 Lists List assigns an index (an integer ) to each element stored Indices of elements are: 0 for the element at the beginning of the list, 1 for the next element … and so on Lists permit duplicate elements They are distinguished by their position in the list Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 6 ++ SKIP++ Sets Set: a collection with no notion of position within the collection for stored elements. Sets do not permit duplicate elements. Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7 ++ SKIP++ Maps A map is a collection of pairs of objects: 1.A value: this is the object to be stored. 2.A key: this is another object associated with the value, and which can be used to quickly find the value within the collection. A map is really a set of keys, with each each key having a value attached to it. Maps do not allow duplicate keys. Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8 Part of the JCF Hierarchy Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 The Collection Interface Comments on the Collection Interface: Lists and Sets are similar in many ways The Collection Interface describes the operations that are common to both Maps are fundamentally different from Lists and Sets and are described by a different interface Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 Some Methods in the Collection Interface MethodDescription add(o : E) : booleanAdds an object o to the Collection. Returns true if o is successfully added to the collection, false otherwise. clear() : voidRemoves all elements from the collection. contains(o : Object): boolean Returns true if o is an element of the collection, false otherwise. isEmpty() : booleanReturns true if there are no elements in the collection, false otherwise. iterator() : Iterator Returns an object called an iterator that can be used to look at all elements stored in the collection. remove(o : Object) : boolean Removes the object o from the collection and returns true if the operation is successful, false otherwise. size() : intReturns the number of elements currently stored in the collection.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11 Iterators Iterator -- an object associated with a collection. Provides methods for fetching the elements of the collection, one at a time, in some order. Iterators also have a method for removing from the collection the last item fetched Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12 AbstractCollection The AbstractCollection class provides a skeleton implementation for a Collection class By implementing many of the methods of the Collection interface. We can create our own collection class by providing implementations for: iterator() size() and overriding add(o : Object) Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Lists

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14 The List Interface The List interface is derived from the Collection interface Derived by adding operations that are specific to the position-based, index-oriented nature of a list Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 15 List Interface Methods List interface has methods for: adding elements to the list removing elements from the list based on the index of the element Also has methods for finding the index of an element in the list when the value of an element is known Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16 The List Interface Methods add(index:int, el:E) : voidAdds the element el to the collection at the given index. Throws IndexOutOfBoundsException if index is negative, or greater than the size of the list. get(index:int):EReturns the element at the given index, or throws IndexOutBoundsException if index is negative or greater than or equal to the size of the list. indexOf(o:Object):intReturns the least (first) index at which the object o is found; returns -1 if o is not in the list. lastIndexOf(o:Object):intReturns the greatest (last) index at which the object o is found; returns -1 if o is not in the list. listIterator():ListIterator Returns an iterator specialized to work with List collections. remove(index:int):ERemoves and returns the element at the given index; throws IndexOutOfBoundsException if index is negative, or greater than or equal to the size of the list. set(index:int, el:E):EReplaces the element at index with the new element el.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 17 AbstractList AbstractList -- an abstract class that provides a skeletal implementation of a List collection It extends AbstractCollection and implements the List interface It is the abstract superclass for the concrete classes ArrayList and Vector Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18 ArrayList ArrayList is an array-based list So, internally, ArrayList uses an array to store its elements When it gets full, a new, bigger array is created, and the elements are copied to the new array Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 19 ++SKIP++ Vector Vector is also an array-based list So, internally, Vector uses an array to store its elements When it gets full, a new, bigger array is created, and the elements are copied to the new array Vector has higher overhead than ArrayList because Vector is synchronized to make it safe for use in programs with multiple threads Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 20 The Iterator Interface Iterators are objects implementing the Iterator interface Iterator interface specifies the following methods: hasNext() : boolean next() : E remove() : void The remove() method is optional, so not all iterators have it. Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21 Methods of the Iterator Interface MethodDescription hasNext() : booleanReturns true if there is at least one more element from the collection that can be returned, false otherwise. next() : EReturns the next element from the collection. remove() : voidRemoves from the collection the element returned by the last call to next(). This method can be called at least one time for each call to next().

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 22 AbstractSequentialList and LinkedList Array-based lists have high overhead for inserting or deleting elements in the middle of the list (i.e., at positions that are not at the beginning or the end of the list) LinkedList eliminates this high overhead LinkedList is a concrete class It stores elements in a way that eliminates the high overhead of adding to, and removing from positions in the middle of the list LinkedList extends AbstractSequentialList, which in turn, extends AbstractList Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 23 Using the Concrete List Classes The concrete classes ArrayList, Vector, and LinkedList work in similar ways but have different performance characteristics Because they all implement the List interface, you can use List interface references to instantiate and refer to the different concrete classes Using a List interface instead of the concrete class reference allows you to later switch to a different concrete class to get better performance (should you need to do so) Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24 Example: Switching from ArrayList to Linked List Using List interface reference to instantiate ArrayList import java.util.*; public class Test1 { public static void main(String [ ] args) { List nameList = new ArrayList (); String [ ] names = {"Ann", "Bob", "Carol"}; // array // Add (from array) to ArrayList for (int k = 0; k < names.length; k++) nameList.add(names[k]); // Display contents of ArrayList for (int k = 0; k < nameList.size(); k++) System.out.println(nameList.get(k)); } Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 25 Continuing - Example: Switching from ArrayList to Linked List Because we used a List reference to refer to the concrete class objects, we can easily switch from an ArrayList (the previous slide) to a LinkedList (the next slide) The only change is in the class used to instantiate the collection Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 26 Using List interface reference to instantiate LinkedList import java.util.*; public class Test2 { public static void main(String [ ] args) { List nameList = new LinkedList (); String [ ] names = {"Ann", "Bob", "Carol"}; // array // Add (from array) to linked list for (int k = 0; k < names.length; k++) nameList.add(names[k]); // Display contents of linked list for (int k = 0; k < nameList.size(); k++) System.out.println(nameList.get(k)); } Continuing - Example: Switching from ArrayList to Linked List Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 27 Using an Iterator To use an iterator with a collection (code listing CL 18-2, p.1065): 1.Call the iterator():Iterator method To retrieve an iterator object 2.Use the hasNext():boolean method To see if there still remain elements to be returned Then use the next():E method To return the next available element 3.If desired, use the remove():void method To remove the element returned by next() remove() removes the element returned by the last call to next() remove() can be called at most one time for each call to next() Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 28 Using an Iterator import java.util.*; public class Test3 { public static void main(String [ ] args) { List nameList = new ArrayList (); // an ArrayList String [ ] names = {"Ann", "Bob", "Carol"}; // an array // Add (from array) to ArrayList (not using the iterator) for (int k = 0; k < names.length; k++) nameList.add(names[k]); // iterator NOT used // Display contents of ArrayList using an iterator Iterator iter = nameList.iterator(); // get the iterator, call it iter while (iter.hasNext()) // use the iterator iter System.out.println(iter.next()); } Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 29 ListIterator The ListIterator extends Iterator (Fig. 18-6, p.1064) Among others, ListIterator adds methods for moving backward through the list In addition to the methods for moving forward that are provided by Iterator hasPrevious() : boolean previous() : E Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 30 Some ListIterator Methods MethodDescription add(el:E):voidAdds el to the list at the position just before the element that will be returned by the next call to the next() method. hasPrevious():booleanReturns true if a call to the previous() method will return an element, false if a call to previous() will throw an exception because there is no previous element. nextIndex():intReturns the index of the element that would be returned by a call to next(), or the size of the list if there is no such element. previous():EReturns the previous element in the list. If the iterator is at the beginning of the list, it throws NoSuchElementException. previousIndex():intReturns the index of the element that would be returned by a call to previous(), or -1. set(el:E):voidReplaces the element returned by the last call to next() or previous() with a new element el.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 31 Iterator Positions Think of an iterator as having a cursor position that is initially just before the element that will be returned by the first call to next() A call to next() puts the cursor just after the element returned, and just before the element that will be returned by the next call to next() At any time, in a ListIterator, the cursor is in between two list elements: a call to previous() will skip backward and return the element just skipped a call to next() will skip forward and return the element just skipped Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 32 Iterator and ListIterator Exceptions A call to previous() throws NoSuchElementException when there is no element that can be skipped in a backward move A call to next() throws NoSuchElementException when there is no element that can be skipped in a forward move Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 33 Example Use of a ListIterator import java.util.*; public class Test4 { public static void main(String [ ] args) { List nameList = new ArrayList (); String [ ] names = {"Ann", "Bob", "Carol"}; // an array // Add (from names array) to ArrayList using a ListIterator ListIterator iter = nameList.listIterator(); for (int k = 0; k < names.length; k++) iter.add(names[k]); // cf. method “add” -Table 18-5, p.1065 // Get a new ListIterator for printing (need to start from names[0]) iter = nameList.listIterator(); while (iter.hasNext()) System.out.println(iter.next()); } Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34 Enhanced For Loop The enhanced for loop can be used with any collection The compiler converts the enhanced for loop into a traditional loop that uses the collection’s iterator Example (cf. Code Listing 18-3) System.out.println("\nThe names in the list."); for (String element : nameList) { System.out.println(element); } Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley SKIP Sets Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley SKIP Maps Updated by L. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Collections Class © 2014 Leszek T. Lilien See Section 8.5, p.1109 Some static methods of the Collections class Example of use of the static methods: Code Listing © 2014 Leszek T. Lilien

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The End Updated by L. Lilien © 2014 Leszek T. Lilien Updated by L. Lilien