Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Stacks, Queues, and Linked Lists
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Chapter 7 – Arrays.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
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.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 19 Java Data Structures
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Copyright © Texas Education Agency, Advanced Computer Programming Data Structures: Collections.
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.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
(c) University of Washington14-1 CSC 143 Java Collections.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
ArrayList, Multidimensional Arrays
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Chapter 18 Java Collections Framework
Data structures Abstract data types Java classes for Data structures and ADTs.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection.
Holding Your Objects Generics and type-safe containers One of the problems of using pre-Java SE5 containers was that the compiler allowed.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
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.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
Chapter 12: Collections by Lewis and Loftus (Updated by Dan Fleck) Coming up: Collections.
Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Chapter 15 Linked Data Structures Slides prepared by Rose Williams, Binghamton University Kenrick Mock University of Alaska Anchorage Copyright © 2008.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Recitation 5 Enums and The Java Collections classes/interfaces 1.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
CSE 1201 Object Oriented Programming ArrayList 1.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
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,
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
Queues CS 367 – Introduction to Data Structures. Queue A queue is a data structure that stores data in such a way that the last piece of data stored,
The ArrayList Data Structure Standard Arrays at High Speed!
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
JAVA COLLECTIONS LIBRARY
TCSS 143, Autumn 2004 Lecture Notes
Object Oriented Programming in java
ArrayLists 22-Feb-19.
Collections Framework
Review: libraries and packages
TCSS 143, Autumn 2004 Lecture Notes
Presentation transcript:

Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The ArrayList Class How to Create an ArrayList Object Adding Elements to an ArrayList Object How to Access an Element Within an ArrayList How to Update an ArrayList Object Additional ArrayList Methods Printing or Concatenating an ArrayList Storing Primitives in an ArrayList ArrayList Example Using Anonymous Objects and a For-Each Loop ArrayList Objects Versus Standard Arrays 1

Chapter 10 – ArrayList s and an Introduction to the Java Collections Framework The LinkedList Class The List Interface Comparing Method Execution Times Queues, Stacks, and the ArrayDeque Class Overview of the Java Collections Framework Collections Example – Information Flow in a Network of Friends 2

The ArrayList Class The ArrayList class provides the basic functionality that comes with a standard array, plus it provides additional functionality. The basic functionality: An ArrayList stores an ordered collection of values and allows access to the values via an index. The added functionality: An ArrayList grows and shrinks dynamically by inserting and deleting elements at any specified location. 3

How to Create an ArrayList Object The ArrayList class is defined in the Java API's java.util package, so for files that use the ArrayList class, import it like this: import java.util.ArrayList; To initialize an ArrayList reference variable, in a declaration, use this syntax: ArrayList reference-variable = new ArrayList<>(); For example, here's how to initialize an ArrayList reference variable named students : ArrayList students = new ArrayList<>(); Use angled brackets to surround the type for the elements, and the type must be a class name (not a primitive). Use empty angled brackets (the diamond operator). 4

How to Create an ArrayList Object Let's compare the syntaxes for creating ArrayList objects, regular objects, and standard arrays. Here's the same ArrayList example as before: ArrayList students = new ArrayList<>(); Here's an object example: Mouse gus = new Mouse(); Here's a standard-array example: Student[] students = new Student[100]; 5

Adding Elements to an ArrayList Object To add an element to the end of an ArrayList object, use this syntax: ArrayList-reference-variable.add( item ); The item that's added must be the same type as the type specified in the ArrayList 's declaration. Write a code fragment that creates this ArrayList object: computerScientists 0"Ada Lovelace" 1"Grace Hopper" 2"Marissa Mayer" 6

Java API API stands for application programming interface. The Java API is the interface to the huge library of pre-built Java classes. As a programmer, you don't need to know the internals of those classes; you just need to know how to use them. Or said another way, you just need to know how to interface with them. To interface with them, you need to use their public methods. To use a method, you need to know what type of argument(s) to pass to it and what type of value it returns. A method's API shows the method's parameters and its return type. The standard way to show that information is to show the method's heading. For example, here's the API heading for the Math class's pow method: public static double pow(double num, double power) 7

How to Access an Element Within an ArrayList With standard arrays, you use square brackets to access and update an element. ArrayList objects don't use square brackets. Instead, they use a get method to access an element and a set method to update an element. Here's the API heading for the ArrayList 's get method: public E get(int index) Semantics: The index parameter specifies the position of the desired element within the ArrayList calling object. As with standard arrays, the first element is at position 0, the second element is at position 1, etc. If index refers to a nonexistent element, then a runtime error occurs. If index is valid, then get returns the element at the specified position. 8

How to Access an Element Within an ArrayList Note the E return type for the ArrayList 's get method: public E get(int index) The E stands for element. It represents the data type of the ArrayList 's elements. It's the same as the element-type specified in the ArrayList 's initialization: ArrayList reference-variable = new ArrayList<>(); 9

How to Update an ArrayList Object The set method allows you to assign a value to an existing ArrayList element. Here's its API heading: public E set(int index, E elem) Semantics: The index parameter specifies the position of the element you're interested in. If index refers to a nonexistent element, then a runtime error occurs. If index is valid, then set assigns the elem parameter to the specified element, overlaying whatever was there originally. E represents the data type of the ArrayList 's elements. 10

How to Update an ArrayList Object Draw a picture of the colors ArrayList after this code fragment executes: String mixedColor; ArrayList colors = new ArrayList<>(); colors.add("red"); colors.add("green"); colors.add("blue"); mixedColor = colors.get(0) + colors.get(1); colors.set(2, mixedColor); 11

Additional ArrayList Methods public void add(int index, E elem) Starting with the specified index position, shift the original elements to higher-indexed positions. Then insert the elem parameter at the specified index position. public void clear() Remove all elements from the list. public int indexOf(Object elem) Search for the first occurrence of the elem parameter within the list. If it's found, return its index position. If it's not found, return -1. public boolean isEmpty() Return true if the list contains no elements. public E remove(int index) Remove the element at the specified index position, shift all higher-indexed elements to lower-indexed positions, and return the removed element. public int size() Return the number of elements in the list. Object is a generic class that can be used as a class type for any object. 12

Example ArrayList Program import java.util.ArrayList; public class HungerGames { public static void main(String[] args) { int deceasedIndex; // index of deceased tribute String deceased; // name of deceased tribute ArrayList tributes = new ArrayList<>(); tributes.add("Cato"); tributes.add("Katniss"); tributes.add("Peeta"); tributes.add("Rue"); tributes.add(1, "Finnick"); deceasedIndex = (int) (Math.random() * tributes.size()); deceased = tributes.remove(deceasedIndex); System.out.println(deceased + " is no longer in the game."); System.out.println("Remaining: " + tributes); } // end main } // end HungerGames 14

Printing or Concatenating an ArrayList If you attempt to print or concatenate an ArrayList, the ArrayList returns a comma-separated list of ArrayList elements surrounded by square brackets, []. For example, in the HungerGames program, if Peeta is removed, the last line prints this: Remaining: [Cato, Finnick, Katniss, Rue] 15

Storing Primitives in an ArrayList As mentioned previously, ArrayList s store references. For example, in the HungerGames program, tribe is an ArrayList of strings, and strings are reference types. If you need to store primitives in an ArrayList, you can't do it directly, but you can do it if the primitives are wrapped in wrapper classes. Ever since Java 5.0, the "wrapping" process has been done behind the scenes. For ArrayList s, it's done automatically if a wrapper class is used in an ArrayList declaration. The StockAverage program on the next slide reads int stock values and stores them in an ArrayList. After all stock values are entered, the program calculates the average stock value. Why is an ArrayList appropriate for calculating a stock average? 16

Storing Primitives in an ArrayList import java.util.Scanner; import java.util.ArrayList; public class StockAverage { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); ArrayList stocks = new ArrayList<>(); double stock; // a stock value double stockSum = 0; // sum of stock values System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble(); while (stock >= 0) { stocks.add(stock); System.out.print("Enter a stock value (-1 to quit): "); stock = stdIn.nextDouble(); } // end while Must be a wrapper class, not a primitive. Automatic boxing (“autoboxing”) takes place here. 17

Storing Primitives in an ArrayList for (int i=0; i<stocks.size(); i++) { stock = stocks.get(i); stockSum += stock; } if (stocks.size() != 0) { System.out.printf("\nAverage stock value = $%.2f\n", stockSum / stocks.size()); } } // end main } // end class StockAverage Where does automatic unboxing take place? 18

ArrayList Example Using Anonymous Objects and a For-Each Loop When storing objects in an ArrayList, it's common to create an object and add it to the ArrayList all in the same statement. For example, the upcoming BearStore program stores Bear objects in an ArrayList. In storing a Bear object, the program creates a Bear object and adds it to the bears ArrayList, all in the same statement: bears.add(new Bear("Acme", "brown teddy")); An anonymous object is an object that's instantiated, but it's not stored in a variable (and with no variable, there's no name for it; thus, we say it's "anonymous"). 19

ArrayList Example Using Anonymous Objects and a For-Each Loop import java.util.Scanner; import java.util.ArrayList; public class BearStore { ArrayList bears = new ArrayList<>(); //********************************************************** // Fill store with specified number of standard teddy bears. public void addStdBears(int num) { for (int i=0; i<num; i++) { bears.add(new Bear("Acme", "brown teddy")); } } // end addStdBears anonymous object 20

ArrayList Example Using Anonymous Objects and a For-Each Loop //********************************************************** // Fill store with specified number of customized bears. public void addUserSpecifiedBears(int num) { for (int i=0; i<num; i++) { bears.add(getUserSpecifiedBear()); } } // end addUserSpecifiedBears //********************************************************** // Prompt user for a customized bear name and return bear. private Bear getUserSpecifiedBear() { Scanner stdIn = new Scanner(System.in); String maker, type; System.out.print("Enter bear's maker: "); maker = stdIn.nextLine(); System.out.print("Enter bear's type: "); type = stdIn.nextLine(); return new Bear(maker, type); } // end getUserSpecifiedBear anonymous object 21

ArrayList Example Using Anonymous Objects and a For-Each Loop //********************************************************** // Print all the bears in the store. public void displayInventory() { for (Bear bear : bears) { bear.display(); } } // end displayInventory //********************************************************** public static void main(String[] args) { BearStore store = new BearStore(); store.addStdBears(3); store.addUserSpecifiedBears(2); store.displayInventory(); } // end main } // end BearStore class 22

ArrayList Example Using Anonymous Objects and a For-Each Loop public class Bear { private final String MAKER; // bear's manufacturer private final String TYPE; // type of bear //********************************************************** public Bear(String maker, String type) { MAKER = maker; TYPE = type; } public void display() { System.out.println(MAKER + " " + TYPE); } } // end Bear class 23

Anonymous Objects The bear store program contains several examples of using anonymous objects. In general, you'll see anonymous objects being used in two circumstances: Passing a newly created object into a method or constructor. For example: bears.add(new Bear("Acme", "brown teddy")); Returning a newly created object from a method. For example: return new Bear(maker, type); 24

For-Each Loop Note the for-each loop in the BearStore' s displayInventory method: public void displayInventory() { for (Bear bear : bears) { bear.display(); } } // end displayInventory For-each loop syntax for an ArrayList : for ( : ) Read this as "for each bear in bears, …" For each iteration through the loop, bear accesses the next element in the bears ArrayList. 25

For-Each Loop Note that using the for-each loop is an option, not a requirement. Here's an alternative displayInventory implementation that uses a standard for loop: public void displayInventory() { for (int i=0; i<bears.size(); i++) { bears.get(i).display(); } } // end displayInventory The for-each loop implementation is preferred because it is simpler. 26

ArrayList Objects Versus Standard Arrays Benefits of an ArrayList Over a Standard Array Benefits of a Standard Array Over an ArrayList 1. It's easy to increase the size of an ArrayList – just call add. 1. A standard array uses []'s to access array elements (which is easier than using get and set methods). 2. It's easy for a programmer to insert or remove an element to or from the interior of an ArrayList – just call add or remove and specify the element's index position. 2. A standard array is more efficient with storing primitive values. 27

The LinkedList Class A linked list is like an ArrayList, in that in holds a collection of related data, but instead of using an underlying array to store the data, it uses a chain of references: 28

The List Interface ArrayList and LinkedList implement many of the same methods, like: get, set, add, remove, clear, and size. That’s because they both implement the same List interface. In Java API documentation, you’ll see: public class ArrayList implements List public class LinkedList implements List stand for element type. implements means the class promises to implement all methods specified by the interface. 29

The List Interface - continued In the past, you’ve declared variables with a primitive type or a class name at the left, like this: double distance; Student student; You can also declare a variable with an interface at the left, like this: List iPhoneApps; First, you could assign an ArrayList object to iPhoneApps. Then, later, you could assign a LinkedList object to the same variable: iPhoneApps = new ArrayList ;... iPhoneApps = new LinkedList ; The same List method call would do the same kind of thing with either type of collection, but of course, the detailed implementations would differ. 30

LinkedList vs. ArrayList Performance With a LinkedList, It’s easiest to find, add, or remove elements that are near one of the two ends. Once an element has been found, it’s easier to remove it from a LinkedList (change a pair of references) than from an ArrayList (shift all higher elements to lower array indices). However, finding an indexed element is much slower in a LinkedList than in an ArrayList, because: Instead of jumping right to the indexed position, the computer must step in from an end until the step count equals the index number (when starting at the head) or equals the length minus the index number (when starting at the tail). 31

Measuring Method Execution Time Measure the average time to get each element at a random index and then set each element at a different random index. Assume a getIndices(length) helper method returns an array of all integers between zero and length in a random sequence with no duplications. First do it for an ArrayList. Then do it for a LinkedList. public static void main(String[] args) { String operationType = "average get and set time"; int length = 1000; int[] indicesA = getIndices(length); int[] indicesB = getIndices(length); ArrayList list = new ArrayList<>(); Double element; long time0, time1; 32

A getIndices method (hidden) private static int[] getIndices (int length) { Random random = new Random(); ArrayList integers = new ArrayList<>(); int[] indices = new int[length]; for (int i=0; i<length; i++) { integers.add(random.nextInt(i+1), new Integer(i)); } for (int i=0; i<length; i++) { indices[i] = integers.get(i); } return indices; } // end getIndices 33

Measuring Method Execution Time // Populate the list for (int i=0; i<length; i++) { list.add(new Double(i)); } To determine a method’s execution time, surround the method call with calls to System.nanoTime(), which returns current time in nanoseconds (billionths of a second): time0 = System.nanoTime(); for (int i=1; i<length; i++) { element = list.get(indicesA[i]); list.set(indicesB[i], element); } time1 = System.nanoTime(); 34

Comparing Method Access Times System.out.println(list.getClass()); System.out.printf("for length = %d, %s = %,d ns\n", length, operationType, (time1 - time0) / length); } // end main Output : class java.util.ArrayList for length = 1000, average get and set time = 174 ns Replace ArrayList by LinkedList and repeat, to obtain: Output: class java.util.LinkedList for length = 1000, average get and set time = 1,455 ns 35

Comparing Method Mutate Times Substitute: String operationType = "average remove and add time"; And replace the for loop body with this: element = list.remove(indicesA[i]); list.add(indicesB[i], element); Then the comparison generates results like these: Output : class java.util.ArrayList for length = 1000, average remove and add time = 1,082 ns Replace ArrayList by LinkedList and repeat, to obtain: Output: class java.util.LinkedList for length = 1000, average remove and add time = 2,543 ns 36

Queues After adding a, b, and then c: After a remove operation: After adding d: bcd front back abc front back b front c back A queue is a first-in first-out (FIFO) waiting line. We add elements to the back (tail), and we remove elements from the front (head). 37

Queues − continued Although we could implement a queue with a LinkedList or an ArrayList, Java’s ArrayDeque is more efficient. An ArrayDeque is backed by an array. The backing array’s length is initially 16, and its length doubles each time the current length is inadequate. The backing array is circular – links connect opposite ends. Pointers identify current head and tail elements. Adding increments tail pointer. Deleting increments head pointer. The ArrayDeque class implements the Deque (pronounced “deck”) interface. To access Java’s Deque interface and ArrayDeque class: import java.util.*; // for Queue and ArrayDeque 38

Restaurant Queue Example public static void main(String[] args) { String servedPerson; // from the queue's head Queue chipotlesQueue = new ArrayDeque<>(); chipotlesQueue.add("Alexa"); chipotlesQueue.add("Carolyn"); while (!chipotlesQueue.isEmpty()) { servedPerson = chipotlesQueue.remove(); System.out.println("What is your order, " + servedPerson + "?"); } } // end main 39

Stacks After pushing a, b, and then c: After a pop operation: After pushing d: c b a b a d b a top A stack is a last-in first-out (LIFO) storage container. We add (push) and remove (pop) elements at the top. 40

Driveway-Parking Stack Example /************************************************************* * DrivewayParking.java * Dean & Dean * * This program uses stacks to help a driveway parking service. *************************************************************/ import java.util.*; // ArrayDeque, Scanner public class DrivewayParking { private ArrayDeque driveway1 = new ArrayDeque<>(); private ArrayDeque driveway2 = new ArrayDeque<>(); //********************************************************* public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); char action; String licensePlate; DrivewayParking attendant = new DrivewayParking(); 41

Driveway-Parking Stack Example do { attendant.describeDriveways(); System.out.print("Enter +license to add, " + "-license to remove, or q to quit: "); licensePlate = stdIn.nextLine(); action = licensePlate.charAt(0); licensePlate = licensePlate.substring(1); switch (action) { case '+': attendant.parkCar(licensePlate); break; case '-': if (!attendant.getCar(licensePlate)) System.out.println("Sorry, couldn't find it."); } // end switch } while (action != 'q'); } // end main 42

Driveway-Parking Stack Example public void describeDriveways() { System.out.println("driveway1 " + driveway1); System.out.println("driveway2 " + driveway2); } // end describeDriveways() //********************************************************* // This method parks a car in the least full driveway. private void parkCar(String licensePlate) { if (driveway1.size() <= driveway2.size()) driveway1.push(licensePlate); else driveway2.push(licensePlate); } // end parkCar 43

Driveway-Parking Stack Example private boolean getCar(String licensePlate) { String otherPlate; if (driveway1.contains(licensePlate)) { otherPlate = driveway1.pop(); while (!otherPlate.equals(licensePlate)) { driveway2.push(otherPlate); otherPlate = driveway1.pop();} return true; } else if (driveway2.contains(licensePlate)) { otherPlate = driveway2.pop(); while (!otherPlate.equals(licensePlate)) { driveway1.push(otherPlate); otherPlate = driveway2.pop();} return true; } else return false; } // end getCar } // end class DrivewayParking 44

Driveway-Parking Stack Example Output: driveway1 [] driveway2 [] Enter +license to add, -license to remove, or q to quit: driveway1 [1234] driveway2 [] Enter +license to add, -license to remove, or q to quit: driveway1 [1234] driveway2 [2345] Enter +license to add, -license to remove, or q to quit: driveway1 [3456, 1234] driveway2 [2345] Enter +license to add, -license to remove, or q to quit: driveway1 [] driveway2 [3456, 2345] Enter +license to add, -license to remove, or q to quit: q 45

Java Collections Framework The Java collections framework has two interface hierarchies, the collection hierarchy, and the map hierarchy. The Collection interface specifies methods common to the List, Queue, and Set interfaces, like add, contains, i sEmpty, set, size, and remove. All classes that implement the Collection interface provide a one-parameter constructor that converts any type of collection to any other type of collection. The collection hierarchy includes a special kind of queue, called a priority queue, which inserts higher priority elements closer to the head of the queue. A map uses a unique key, like an id number, to provide rapid access to other (more complex) objects. 46

Java Collections Framework > List > Set > NavigableSet HashSet ArrayDeque > Queue > Collection ArrayList TreeSet > SortedSet PriorityQueue Collections LinkedList LinkedHashSet > Deque 47

Java Collections Framework − Maps > Map TreeMap HashMap > NavigableMap > SortedMap LinkedHashMap > NavigableSet 48

A map relates an object in a key set to another object that could be in another set, a list, or a queue. A map is like a mathematical function. You provide an independent key, and it returns a dependent value. To add a value of type V identified by a key of type K to a Java Map, use this method: public V put(K key, V value) To retrieve a reference to the value identified by key, use this method: public V get(Object key) To remove and return the value identified by key, use this method: public E remove(K key) Java Collections Framework − Maps 49

Collections Example – Information Flow in a Network of Friends Assume: A set of citizens. Each citizen is connected to a random set of friends. Each friendship is mutual (a bidirectional connection). Give one citizen a new message with request to pass it on to all his or her friends, asking them to do likewise. Continue until all who can be reached have been informed. Major operations: build network; distribute message. Details: Store set of citizens with a set of friends for each citizen. Make sure dissemination process terminates: Add each newly informed citizen to a sender’s queue. Remove citizens from that queue to propagate message to that sender’s friends. Do not add previously informed citizens to sender’s queue. As more citizens become informed, fewer are added to the queue, and it empties. 50

CommunityDriver.java /******************************************************* * CommunityDriver.java * Dean & Dean * * Create citizens & friendships and propagate a message. *******************************************************/ import java.util.*; // for Scanner, Map, and Set public class CommunityDriver { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); Community community; Map citizens; Set informedCitizens; 51

CommunityDriver.java − continued // Create the network. System.out.print( "Enter citizen & relation quantities: "); community = new Community(stdIn.nextInt(), stdIn.nextInt()); citizens = community.getCitizens(); System.out.println("Citizen\tFriends"); for (Integer id : citizens.keySet()) { // Citizen’s toString method displays citizen info: System.out.println(citizens.get(id)); } 52

CommunityDriver.java − continued // Propagate a message through it. System.out.print("Enter information source ID: "); informedCitizens = community.spreadWord(stdIn.nextInt()); System.out.println("Citizen\tDelay"); for (Integer citizenID : informedCitizens) { System.out.printf("%d\t%d\n", citizenID, citizens.get(citizenID).getDelay()); } } // end main } // end CommunityDriver 53

Community.java − constructor private Map citizens = new HashMap<>(); public Community(int citizenQuantity, int relationQuantity) { Random random = new Random(0); Citizen citizen; // any citizen object int self, other; // ID numbers for (int i=0; i<citizenQuantity; i++) { citizen = new Citizen(); citizens.put(citizen.ID, citizen); // ID is public } for (int j=0; j<relationQuantity; j++) { self = random.nextInt(citizens.size()); do { other = random.nextInt(citizens.size()); } while (other == self || citizens.get(self).getFriends().contains(other)); citizens.get(self).addFriend(other); citizens.get(other).addFriend(self); } } // end constructor 54

Community.java − spreadWord method public Set spreadWord(int sender) { Set informedCitizens = new LinkedHashSet<>(); Queue sendersQueue = new ArrayDeque<>(); citizens.get(sender).setDelay(0); // for originator informedCitizens.add(sender); sendersQueue.add(sender); do { sender = sendersQueue.remove(); for (Integer friend : citizens.get(sender).getFriends()) { if (!informedCitizens.contains(friend)) { citizens.get(friend).setDelay( citizens.get(sender).getDelay() + 1); informedCitizens.add(friend); sendersQueue.add(friend); } } // end for each uninformed friend } while (!sendersQueue.isEmpty()); return informedCitizens; } // end spreadWord 55

Citizen.java /************************************************************* * Citizen.java * Dean & Dean * * This represents an element in a network of citizens. *************************************************************/ import java.util.*; // Set & TreeSet public class Citizen { private static int nextID = 0; // for unique IDs public final int ID = nextID++; // cannot change! private Set friends = new TreeSet<>(); private int delay; //********************************************************** // public String toString() { return String.format("%d\t%s", ID, friends); } // end toString } // end class Citizen 56

Example Network of Friends Enter citizen & relation quantities: Citizen Friends 0 [8, 9, 15] 1 [4, 8] 2 [4, 5] 3 [9] 4 [1, 2, 5, 10] 5 [2, 4, 11] 6 [9, 10] 7 [] 8 [0, 1] 9 [0, 3, 6, 12] 10 [4, 6] 11 [5, 13] 12 [9] 13 [11] 14 [15] 15 [0, 14] 57

Example Message Dissemination Enter information source ID: 4 Citizen Delay