Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections...

50
Generic Collections CSC 295-01 Spring 2019 Howard Rosenthal

Transcript of Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections...

Page 1: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Generic CollectionsCSC 295-01Spring 2019

Howard Rosenthal

Page 2: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Course References� Materials for this course have utilized materials in the following documents.

Additional materials taken from web sites will be referenced when utilized.1. http://www.programmedlessons.org/Java9/index.html2. Anderson, Julie and Franceschi Herve, Java Illuminated 5TH Edition,, Jones and

Bartlett, 20193. Bravaco, Ralph and Simonson, Shai, Java programming From The Ground Up,

McGraw Hill, 20104. Deitel, Paul and Deitel, Harvey, Java, How To Program, Early Objects, Eleventh

Edition, Pearson Publishing, 20175. Gaddis, Tony, Starting Out With Objects From Control Structures Through

Objects, Pearson Publishing, Version 7, 20196. Horstmann, Cay, Core Java For The Impatient, Addison Wesley- Pearson

Education, 20157. Schmuller, Joseph, Teach Yourself UML In 24 Hours Second Edition, SAMS

Publishing, 20028. Urma, Raoul-Gabriel, Fusco, Mario and Mycroft, Alan, Java 8 in Action:

Lambdas, Streams, and Functional-Style Programming, Manning Publishing, 2014

9. Wirfs-Brock, Rebecca, Wilkerson, Brian and Wiener, Laura, Designing Object-Oriented Software, Prentice Hall, 1990

2

Page 3: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Lesson Goals

� Learn what Collections are� Use class Arrays for array manipulation� Briefly review wrapper classes, boxing and unboxing� Learn to use pre-built generic data structures� Learn about iterators� Understand the List Interface and related classes� Use algorithms of the Collections class to process

collections� Understand the Queue interface and PriorityQueue classs� Understand the Set and SortedSet interface and HashSet,

LinkedHashSet and TreeSet classes� Understand the Map interface and HashMap, TreeMap and

LinkedHashMap classes

3

Page 4: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

4

Page 5: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The Collections Framework� The Collections Framework is a unified architecture for representing

and manipulating collections, enabling them to be manipulated independently of the details of their representation.

� It contains prebuilt generic data structures� It reduces programming effort while increasing performance. � It enables interoperability among unrelated APIs, reduces effort in

designing and learning new APIs, and fosters software reuse.� It allows interoperability between APIs

� The framework is based on more than a dozen collection interfaces. � It includes implementations of these interfaces and algorithms to

manipulate them.� The interface Collection contains bulk operations for adding, clearing

and comparing objects in a collection. � This includes adding a list of elements, or even a whole Collection, to a

Collection� Don’t confuse the Collection interface with the Collections class� Helpful reference For reading Oracle Java documentationhttps://docs.oracle.com/javase/tutorial/java/generics/types.html

5

Page 6: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Describing The Collections Class And Collections Objects� This Collections class consists exclusively of static methods that operate on or

return collections. � It contains polymorphic algorithms that operate on collections, "wrappers",

which return a new collection backed by a specified collection, and a few other odds and ends.

� The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null.

� The "destructive" algorithms contained in this class, that is, the algorithms that modify the collection on which they operate, are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s), such as the set method.

� A collection is a data structure – actually an object – that can hold references to other objects� Usually collections contain references to objects of any type that has an is-a

relationship� In other words it takes advantage of polymorphism – i.e an ArrayList of a certain

type can have as member any subclass of that type� Collections cannot manipulate variables of primitive data

� This is why we use wrapper classes for the primitive variables, taking advantage of autoboxing and unboxing, when needing to use a Collection class (i.e. ArrayList) with objects

� See IntegersInArrayList.java and CharacterArrayListExample.java

� See https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html6

Page 7: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The Java Collection Framework Hierarchy For The Collection interface

7

Page 8: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Polymorphism Example With ArrayList� In the example below assume we create the ArrayList:

ArrayList <Auto> autotList = new ArrayList<Auto>();� Then not only Auto objects, but Ford, Honda, Volvo, Civic,

Accord and Pilot objects, etc. can be added to the ArrayList autoList

� Remember that if you retrieve an object from autoList you may need to cast downward to exact type in order to access it’s data and methods

8

Honda

Auto

Ford Volvo

Civic Accord Pilot

Page 9: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Some Collections Framework Interfaces

9

The collections framework classes and interfaces are all found in the java.util package

Page 10: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Using The Iterator And iterator() Method– An Introduction� Often you wish to access the elements of an ArrayList one by one, in

order� You could write a counting loop � You can use an Iterator object.

� The Interface Collection provides a method that returns an Iterator object, which allows a program to walk through the collection and remove elements from the collection during the iteration.

� To get an Iterator object, use the iterator method of ArrayList:

Iterator<E> iterator() // Returns an iterator i.e.Iterator<String> iter = names.iterator(); //creates an Iterator object

� ArrayList implements the Iterable interface (to be discussed later).� iterator() is the only method in this interface

� An iterator object is used to visit the elements of a list one by one� It visits only the cells that have data (so you don't need to worry about

going past the end of data)� This is more convenient than writing a loop

10

Page 11: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Iterator Methods� An iterator implements the Iterator<E> interface, which has the

following methods:boolean hasNext() // Returns true if not all elements have been visited E next() // Returns the next element of the list, a reference to type E void remove() // Remove from the list the element just returned by next()

� You need to import the Iterator class:import java.util.Iterator;

� Note: If a collection is modified by one of its methods after an iterator is created for that collection, the iterator becomes invalid� Any operation performed with the iterator fails immediately and

throws an exception. � This is called fast-fail

� Fast-fail iterators help ensure that a modifiable collection is not manipulated by two or more threads at the same time.

See ArrayListExampleIterator.java

11

Page 12: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Using The Enhanced For Loop With The ArrayList Class

� The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implement the Iterable interface, such as ArrayList

for (ClassName currentObject: ArrayListName){

Process currentObject }

� The program does the same thing as we showed with the Iterator� The enhanced for loop accesses the String references in names and assigns

them one-by-one to currentObject� With an enhanced for loop there is no danger an index will go out of bounds

� The enhanced for loop only visits those cells that are not empty, beginning with cell zero

� Since an ArrayList never has gaps between cells, all occupied cells are visited

See ArrayListExampleIterator.java

12

Page 13: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

13

Page 14: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Understanding Lists (1)

� A List (sometimes called a sequence) is an ordered Collection that can contain duplicate elements. � List indices are zero based.

� In addition to the methods inherited from Collection, List provides methods for:� Manipulating elements via their indices� Manipulating a specified range of elements� Searching for elements and obtaining a ListIterator to access the

elements.� Interface List is implemented by several classes, including

ArrayList, LinkedList and Vector. (We discuss LinkedList later)� Autoboxing occurs when you add primitive-type values to

objects of these classes, because they store only references to objects.

See https://docs.oracle.com/javase/8/docs/api/java/util/List.html

14

Page 15: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Understanding Lists (2)

� Class ArrayList and Vector are resizable-array implementations of List. � Inserting an element between existing elements of an

ArrayList or Vector is an inefficient operation. � A LinkedList enables efficient insertion (or removal) of

elements in the middle of a collection, but is much less efficient than an ArrayList for jumping to a specific element in the collection.

� We discuss the architecture of linked lists later.� The primary difference between ArrayList and Vector is

that operations on Vectors are synchronized by default, whereas those on ArrayLists are not. � Unsynchronized collections provide better performance than

synchronized ones. � For this reason, ArrayList is typically preferred over Vector in

programs that do not share a collection among threads.

15

Page 16: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

ArrayList and Iterator

� List method add adds an item to the end of a list. � List method size returns the number of elements. � List method get retrieves an individual element’s value from the

specified index. � Collection method iterator gets an Iterator for a Collection. � Iterator- method hasNext determines whether there are more elements

to iterate through. � Returns true if another element exists and false otherwise.

� Iterator method next obtains a reference to the next element.� Collection method contains determine whether a Collection contains a

specified element.� Iterator method remove removes the current element from a

Collection.� Note: We refer to each ArrayList in this example. This would for

instance allow us to substiture LinkedList for ArrayList if we needed to. Same with the way we implement removeColors method

See CollectionTest.java

16

Page 17: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Type Inference With The <> Notation

� You can use type inferencing with <>, known as diamond notation, in statements that declare and create generic type variations and objects.

� Example:List<String> list= new ArrayList<String>();andList<String> list = new ArrayList<>();are equivalent

list is actually an ArrayList

17

Page 18: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The LinkedList – An Overview

� Linked Lists are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. � The elements are linked using references to addresses. � Each element is known as a node. � Due to the dynamicity and ease of insertions and deletions, they are preferred

over the arrays. � With an ArrayList, insertions and deletions require rewriting all elements after the

insertion� It also has few disadvantages like the nodes cannot be accessed directly instead

we need to start from the head and follow through the link to reach to a node we wish to access.

� To store the elements in a linked list we use a doubly linked list which provides a linear data structure and also used to inherit an abstract class and implement list and deque interfaces.

� In Java, LinkedList class implements the list interface. � The LinkedList class also consists of various constructors and methods like

other java collections.� We demonstrate some of these in LinkedListTest.java

� See https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

18

Page 19: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Inserting A Node In a Doubly Linked List

19

• The dotted lines shows what happens when you insert • Leah between Joshua and Miriam

Page 20: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Array vs. Linked List

20

• The LinkedList class in java is doubly linked• This means it has a reference to the predecessor as well as the successor

Page 21: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

21

Page 22: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Collections class Implements A Number Of Useful Static Methods

22

Method Description

sort Sorts the elements of a Collection in an input listSee CollectionSorting.java or CollectionSorting1.java or(Time.java, TimeComparator.java and SortingTime.java)

reverse Reverses all the elements in a CollectionSee CollectionSorting1.java

shuffle Random shuffling of the elements of a Collection (very good in card simulations) See ShuffleExample.java or (Card.java, DeckOfCards.java and CardShuffleTester.java

fill Sets every element in the Collection to refer to the given argument (see AlgorithmsForCollections.java)

copy Copies the references from one Collection into another List. The destination List must be at least as long as the source List; otherwise, an IndexOutOfBoundsException occurs. (see AlgorithmsForCollections.java)

min Returns the “smallest” element in a Collection, based on the elements comparator (i.e must implement the Comparable interface)

max Returns the “largest” element in a Collection, based on the elements comparator (see AlgorithmsForCollections.java)

binarySearch Locate an item in a sorted Collection using binary search See BinarySearchTest.java

addAll Appends all the elements in an array to a Collection. See AlgorithmsForMoreCollectionMethods.java

frequency Calculates how many Collection elements are equal to the specified element. See AlgorithmsForMoreCollectionMethods.java

disjoint Returns true if two Collections have no elements in common otherwise false. See AlgorithmsForMoreCollectionMethods.java

Page 23: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Type Parameter Naming Conventions

� The following discussion is useful for reading Oracle documentation on Generic Types

� By convention, type parameter names are single, uppercase letters. � This stands in sharp contrast to the variable naming conventions

that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.

� The most commonly used type parameter names are:� E - Element (used extensively by the Java Collections Framework)� K - Key� N - Number� T - Type� V - Value� S,U,V etc. - 2nd, 3rd, 4th types

23

Page 24: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The asList Method For Arrays

� The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array. � This method acts as bridge between array-based and collection-

based APIs, in combination with Collection.toArray(). � The returned list is serializable and implements RandomAccess.� Changes to the returned list "write through" to the array.

� toArray is a method of the Collection interface that converts the elements of any lCollection into a fixed sized array.

� This method also provides a convenient way to create a fixed-size list initialized to contain several elements:� List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

� See AsListDemo1.java

24

Page 25: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The sort Method

� Method sort sorts the elements of a List� The elements must implement the Comparable interface.� The order is determined by the natural order of the elements’ type

as implemented by a compareTo method. � Method compareTo is declared in interface Comparable and is

sometimes called the natural comparison method. � The sort call may specify as a second argument a Comparator object

that determines an alternative ordering of the elements.� Note: in several of the programs we use the Arrays method

asList, which allows you to view an array as a List Collection. � This List view allows you to manipulate the array as if it were a List.

� Useful for adding elements in the array to a List, and for sorting.

25

Page 26: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Using Comparator in Sorting

� The custom Comparator class, named TimeComparator, that implements interface Comparator to compare two Time objects. � Class Time represents times with hours, minutes and seconds.� Class TimeComparator implements interface Comparator, a generic

type that takes one type argument.� A class that implements Comparator must declare a compare

method that receives two arguments and returns a negative integer if the first argument is less than the second, 0 if the arguments are equal or a positive integer if the first argument is greater than the second.

� See Time.java, TimeComparator.java and SortingTime.java

26

Page 27: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Using the binarySearch Method

� static Collections method binarySearch locates an object in a List. � If the object is found, its index is returned. � If the object is not found, binarySearch returns a

negative value. � Method binarySearch determines this negative value by

first calculating the insertion point and making its sign negative.

� Then, binarySearch subtracts 1 from the insertion point to obtain the return value, which guarantees that method binarySearch returns positive numbers (>= 0) if and only if the object is found.

� Binary search can only be used after sorting the list27

Page 28: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

28

Page 29: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The Queue Interface - Overview

� A Queue is a First In First Out (FIFO) data structure. It models a queue in real-life. Yes, the one that you might have seen in front of a movie theater, a shopping mall, a metro, or a bus.� Just like queues in real life, new elements in a Queue data

structure are added at the back and removed from the front. A Queue can be visualized as shown in the figure below.

29

Page 30: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The Queue interface� The Queue interface is available in the java.util package and extends the Collection

interface. � It is used to hold the elements about to be processed and provides various operations like

the insertion, removal etc. � It is an ordered list of objects with its use limited to insert elements at the end of the list

and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.

� Being an interface the queue needs a concrete class for the declaration and the most common classes are the PriorityQueue and LinkedList in Java.� It is to be noted that both the implementations are not thread safe. PriorityBlockingQueue

is one alternative implementation if thread safe implementation is needed. � Important characteristics of Queue are:

� The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept.

� The Java Queue supports all methods of Collection interface including insertion, deletion etc.

� LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used implementations.

� If any null operation is performed on BlockingQueues, NullPointerException is thrown.� BlockingQueues have thread-safe implementations.� The Queues which are available in java.util package are Unbounded Queues� The Queues which are available in java.util.concurrent package are the Bounded Queues.� All Queues except the Deques supports insertion and removal at the tail and head of the

queue respectively. � The Deques support element insertion and removal at both ends.

30

Page 31: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The Queue interface Inheritance Hierarchy

31

Page 32: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The Queue interface Methods� Methods of the Queue interface include:

� add()- This method is used to add elements at the tail of queue. More specifically, at the last of LinkedList if it is used, or according to the priority in case of priority queue implementation.

� peek()- This method is used to view the head of queue without removing it. It returns Null if the queue is empty.

� element()- This method is similar to peek(). It throws NoSuchElementException when the queue is empty.

� remove()- This method removes and returns the head of the queue. It throws NoSuchElementException when the queue is empty.

� poll()- This method removes and returns the head of the queue. It returns null if the queue is empty.

� size()- This method return the no. of elements in the queue.

� See programs QueueExample.java� See https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html

32

Page 33: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The PriorityQueue class Overview� A priority queue in Java is a special type of queue wherein all the

elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.� The front of the priority queue contains the least element according to

the specified ordering, and the rear of the priority queue contains the greatest element.

� When you remove an element from the priority queue, the least element according to the specified ordering is removed first.

33

Page 34: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The PriorityQueue class� A PriorityQueue is used when the objects are supposed to be processed based

on the priority. � It is known that a queue follows First-In-First-Out algorithm, but sometimes

the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play.

� The PriorityQueue is based on the priority heap. � The elements of the priority queue are ordered according to the natural

ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.

� Important points on Priority Queue are as follows:� PriorityQueue doesn’t permit NULL pointers.� We can’t create PriorityQueue of Objects that are non-comparable� PriorityQueue are unbound queues.� The head of this queue is the least element with respect to the specified

ordering. If multiple elements are tied for least value, the head is one of those elements — ties are broken arbitrarily.

� The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

� It inherits methods from AbstractQueue, AbstractCollection, Collection and Object class.

34

Page 35: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The PriorityQueue class Inheritance Hierarchy

35

Page 36: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

PriorityQueue class Constructors� PriorityQueue()

� Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.

� PriorityQueue(Collection c)� Creates a PriorityQueue containing the elements in the specified collection.

� PriorityQueue(int initialCapacity)� Creates a PriorityQueue with the specified initial capacity that orders its

elements according to their natural ordering.� PriorityQueue(int initialCapacity, Comparator comparator)

� Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.

� PriorityQueue(PriorityQueue c)� Creates a PriorityQueue containing the elements in the specified priority

queue.� PriorityQueue(SortedSet c)

� Creates a PriorityQueue containing the elements in the specified sorted set.� See CreatePriorityQueue.java, CreatePriorityQueueStringExample.java, PriorityQueueCustomComparatorExample.java, see PriorityQueueExample.java

36

Page 37: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

37

Page 38: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Set Overview

� A Set is an unordered Collection of unique elements, that includes no duplicates.

� The collections framework contains several Set implementations, including HashSet, LinkedHashSet and TreeSet. � HashSet stores its elements in a hash table, and TreeSet stores its

elements in a tree. � The collections framework also includes the SortedSet interface

(which extends Set) for sets that maintain their elements in sorted order. � Class TreeSet implements SortedSet. � TreeSet method headSet gets a subset of the TreeSet in which every

element is less than the specified value. � TreeSet method tailSet gets a subset in which each element is

greater than or equal to the specified value.� SortedSet methods first and last get the smallest and largest

elements of the set, respectively.

38

Page 39: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

The Set interface Hierarchy

39

Page 40: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Basic Methods Of Set interface

� add( ) -Adds an object to the collection.� clear( ) - Removes all objects from the collection.� contains( ) - Returns true if a specified object is an

element within the collection.� isEmpty( ) - Returns true if the collection has no

elements� iterator( ) -Returns an Iterator object for the

collection, which may be used to retrieve an object. � remove( ) - Removes a specified object from the

collection.� size( ) - Returns the number of elements in the

collection.40

Page 41: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

SortedSet Implementation

� The collections framework also includes the SortedSet interface (which extends Set) for sets that maintain their elements in sorted order. � Class TreeSet implements SortedSet. � TreeSet method headSet gets a subset of the TreeSet in

which every element is less than the specified value. � TreeSet method tailSet gets a subset in which each

element is greater than or equal to the specified value.� SortedSet methods first and last get the smallest and

largest elements of the set, respectively.

41

Page 42: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Tips On Programming With Set (1)� Creating a Set� Always use generics to declare a Set of specific type, e.g. a Set of integer

numbers:Set<String> names = new LinkedHashSet<>();

� Adding elements to a set:� The add()method returns true if the set does not contain the specified element,

and returns false if the set already contains the specified element:Set<String> names = new HashSet<>();names.add("Tom");names.add("Mary"); if (names.add("Peter")) {

System.out.printf("Peter is added to the set\n");} if (!names.add("Tom")) {

System.out.printf("Tom is already added to the set\n");}� This code produces:Peter is added to the setTom is already added to the set

42

Page 43: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Tips On Programming With Set (2)� Removing elements from a Set

� The remove() method removes the specified element from the set if it is present and the method returns true, or false otherwise:

if (names.remove("Mary")) {

System.out.printf("Mary is removed\n");}

� Creating a union of two sets� s1.addAll(s2) — transforms s1 into the union of s1 and s2 with no

duplicate elementsSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 3, 5, 7, 9));Set<Integer> s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));System.out.printf("s1 before union: %s\n”, s1) s1.addAll(s2);System.out.printf("s1 after union: %s\n”, s1);� This code produces:s1 before union: [1, 3, 5, 7, 9]s1 after union: [1, 2, 3, 4, 5, 6, 7, 8, 9]

43

Page 44: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Tips On Programming With Set (3)� Creating an intersection of two sets

� s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2.

Set<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 7, 9));Set<Integer> s2 = new HashSet<>(Arrays.asList(2, 4, 6, 8));System.out.printf("s1 before intersection: %s\n”, s1);s1.retainAll(s2);System.out.printf("s1 after intersection: %s\n”, s1);This code produces:s1 before intersection: [1, 2, 3, 4, 5, 7, 9]s1 after intersection: [2, 4]

44

Page 45: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

45

Page 46: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

What is a Map interface� A Map Is A part of the Java Collection Framework, but is not derived

from the Collection interface� A Map object implements the map interface that maps keys to values.

� A Map cannot contain duplicate keys: � Each key can map to at most one value - It models the mathematical function

abstraction. � The Map interface includes methods for basic operations (such as put, get,

remove, containsKey, containsValue, size, and empty), bulk operations (such as putAll and clear), and collection views (such as keySet, entrySet, and values).

� The Java platform contains three general-purpose Map implementations: � HashMap, TreeMap, and LinkedHashMap. � Their behavior and performance are precisely analogous to HashSet,

TreeSet, and LinkedHashSet, as described in The Set Interface section.� Interface SortedMap extends Map and maintains its keys in sorted

order—either the elements’ natural order or an order specified by a Comparator.

46

Page 47: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Map Interfaces Are A Part Of the Java Collection Framework

47

Page 48: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Maps and Keys

� Maps associate keys to values. � The keys in a Map must be unique, but the associated

values need not be. � If a Map contains both unique keys and unique values, it

is said to implement a one-to-one mapping. � If only the keys are unique, the Map is said to implement

a many-to-one mapping—many keys can map to one value.

� See TreeMapExample.java

48

Page 49: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Properties Class

� Properties is a subclass of Hashtable. � It is used to maintain lists of values in which the key is a

String and the value is also a String.� The Properties class is used by many other Java classes.

For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.

49

Page 50: Lesson 7 - Generic Collections CSC 295-01 Spring 2019€¦ · Lesson Goals Learn what Collections are Use class Arrays for array manipulation Briefly review wrapper classes, boxing

Properties Class Methods� String getProperty(String key)- Returns the value associated with the key. A

null object is returned if the key is neither in the list nor in the default property list.

� String getProperty(String key, String defaultProperty) -Returns the value associated with the key; defaultProperty is returned if the key is neither in the list nor in the default property list.

� void list(PrintStream streamOut) -Sends the property list to the output stream linked to streamOut

� void list(PrintWriter streamOut) -Sends the property list to the output stream linked to streamOut.

� void load(InputStream streamIn) throws IOException -Inputs a property list from the input stream linked to stream

� Enumeration propertyNames( ) - Returns an enumeration of the keys. This includes those keys found in the default property list, too.

� Object setProperty(String key, String value) - Associates value with the key. Returns the previous value associated with the key, or returns null if no such association exist

� void store(OutputStream streamOut, String description) - After writing the string specified by description, the property list is written to the output stream linked to streamOut.

� See PropertiesDemo.java50