Chapter 22 part 1 2 java collections framework
This presentation is the property of its rightful owner.
Sponsored Links
1 / 83

Chapter 22 ( Part 1/2) Java Collections Framework PowerPoint PPT Presentation


  • 73 Views
  • Uploaded on
  • Presentation posted in: General

Chapter 22 ( Part 1/2) Java Collections Framework. Objectives (1). To describe the Java Collections Framework hierarchy (§22.1) To use the common methods defined in the Collection interface for operating sets and lists (§22.2) To use the Iterator interface to traverse a collection (§22.3)

Download Presentation

Chapter 22 ( Part 1/2) Java Collections Framework

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Chapter 22 part 1 2 java collections framework

Chapter 22 (Part 1/2)Java Collections Framework


Objectives 1

Objectives (1)

  • To describe the Java Collections Framework hierarchy (§22.1)

  • To use the common methods defined in the Collection interface for operating sets and lists (§22.2)

  • To use the Iterator interface to traverse a collection (§22.3)

  • To use the JDK 1.5 foreach loop to simplify traversing a collection (§22.3)

  • To discover the Set interface, and know how and when to use HashSet, LinkedHashSet, or TreeSet to store elements (§22.3)


Objectives 2

Objectives (2)

  • To compare elements using the Comparator interface (§22.4)

  • To explore the List interface, and know how and when to use ArrayList or LinkedList to store elements (§22.5)

  • To know how to use the static methods in the Collections class for lists and collections (§22.6)

  • To distinguish Vector and ArrayList, and know how to use Vector and Stack (§22.7)


Objectives 3

Objectives (3)

  • To explore the relationships among Collection, Queue, LinkedList, and PriorityQueue and to create priority queues using the PriorityQueue class (§22.8)

  • To understand the differences between Collection and Map, and know how and when to use HashMap, LinkedHashMap, and TreeMap to store values associated with keys (§22.9)

  • To obtain singleton sets, lists, and maps, and unmodifiable sets, lists, and maps using the static methods in the Collections class (§22.10)


Object oriented data structure 1

Object-Oriented Data Structure (1)

  • In object-oriented thinking, a data structure is an object that stores other objects, referred to as data or elements

  • So some people refer a data structure as a containerobject or a collection object

  • To define a data structure is essentially to declare a class


Object oriented data structure 2

Object-Oriented Data Structure (2)

  • The class for a data structure should use data fields to store data and provide methods to support operations such as insertion and deletion

  • To create a data structure is therefore to create an instance from the class

    • One can then apply the methods on the instance to manipulate the data structure such as inserting an element to the data structure or deleting an element from the data structure


Java collection framework hierarchy

Java Collection Framework Hierarchy

  • A collection is a container object that represents a group of objects, often referred to as elements

  • The Java Collections Framework supports three types of collections

    • sets

    • lists

    • maps


Java collection framework

Java Collection Framework

  • Collection

    • A general interface for any data structure that contains a collection of elements

  • Iterator

    • An interface for the simple iterator ADT

  • List

    • An interface to include list ADT

  • ListIterator

    • An iterator that provides forward and backward traversals

  • Map

    • An interface for mapping keys to values

  • Queue

    • An interface for a queue ADT

  • Set

    • An interface extending Collection to sets


Java collection framework hierarchy set and list

Java Collection Framework Hierarchy – Set and List

inheritance

interface

extends

implements

Page 728

Set , List, and Queue are subinterfaces of Collection


Java collection framework hierarchy map

Java Collection Framework Hierarchy – Map

  • An instance of Maprepresents a group of objects, each of which is associated with a key

  • One can get the object from a map using a key and one has to use a key to put the object into the map


The collection interface

The Collection Interface

The Collection interface is the root interface for manipulating a collection of objects

Composition


Collection interface adding removing methods

Collection Interface Adding/Removing Methods

  • Provides the basic operations for adding and removing elements in a collection

    • addAll– add all the elements in the specified collection

    • removeAll – removes the elements from a collection that are present in the specified collection

    • retainAll – retains elements in a collection that are present in the specified collection

    • clear removes all the elements from a collection


Collection interface query methods

Collection Interface Query Methods

  • Provides the basic operations for querying

    • size – returns the number of elements

    • contains – tests whether the collection contains a particular element

    • containsAll – test whether the collection contains all the elements of a specified collection

    • isEmpty - test whether the collection is empty


Another collection interface method

Another Collection Interface Method

  • toArray() – returns an array representation of the collection


Iterators

Iterators

  • Iterator interface provides a uniform method for traversing elements

    • The iterator method returns an instance of the Iterator interface that provides access to the elements using the next() method and the remove() method to remove the last element returned


Chapter 22 part 1 2 java collections framework

Sets


Convenience classes

Convenience Classes

  • Interface cannot contain concrete methods

  • The virtues of interfaces and abstract classes can be combined by creating an interface with an abstract class that implements it

    • One can use either the interface class or the abstract class which ever is convenient

    • Abstract Collection is a convenience class for the Collection interface

    • AbstractSet is a convenience class for the Set interface


The set interface

The Set Interface

  • The Set interface extends the Collection interface

  • It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements

  • The concrete classes that implement Set interface must ensure that no duplicate elements can be added to the set

    • That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true


The set interface hierarchy

The Set Interface Hierarchy


The abstractset class

The AbstractSet Class

  • The AbstractSet class is a convenience class that implements Set

    • No duplicates allowed

  • The AbstractSet class provides concrete implementations for the equals() and the hashCode() methods

    • The hash code of a set is the sum of the hash code of all the elements in the set


The abstractset class 2

The AbstractSet Class (2)

  • The size() and iterator() methods are not implemented in the AbstractSet class

  • The Java collection provides three concrete class of Set

    • Hashset

    • LinkedHashSet

    • TreeSet

21


The hashset class 1

The HashSet Class (1)

  • The HashSet class is a concrete class that implements Set

  • It can be used to store duplicate-free elements

  • For efficiency, objects added to a hash set need to implement the hashCode() method in a manner that properly disperses the hash code


The hashset class 2

The HashSet Class (2)

Load factor is how full the set is allowed to become before the capacity is increased

When the number of elements exceeds the product of capacity and load factor, the capacity is doubled

By default, the initial capacity is 16 and the load factor is 0.75

(16*.075=12)

A higher load factor decreases the space cost but increases search time

23


The hashset class 3

The HashSet Class (3)

The hashcode() method is defined within the Objectclass

Hashcode rules

The hashcode of two objects must be the same of the objects are equal

Two unequal objects may have the same hashcode but the hashcode() method should be implement to minimize this situation

24


Example using hashset and an iterator

Example: Using HashSet and an Iterator

  • This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list

  • Notes:

    • New York is added twice but is stored only once

    • Set is not ordered

Listing 22.1

TestHashSet

Run


For each loop

for-each loop

One can simplify the code in lines 21-26 without using an iterator, as follows:

for (Object element: set)

System.out.print(element.toString() + " ");

Listing 22.1

26


Using testmethodsincollection

Using TestMethodsInCollection

Since a set is a collection, all methods defined in the collection can be used for sets

See TestMethodsInCollections (Page 732)

27


Using linkedhashset

Using LinkedHashSet

Since a set is a collection, all methods defined in the collection can be used for sets

This example creates a hash set filled with strings, and uses an iterator to traverse the elements in the list

TestLinkedHashSet

Run

Listing 22. 3

28


Sorted sets

Sorted Sets


The sortedset interface and the treeset class

The SortedSet Interface and the TreeSet Class

  • SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted

    • It provides the first() and last() methods

  • TreeSet is a concrete class that implements the SortedSet interface

  • One can use an iterator to traverse the elements in the sorted order


Sorting methods

Sorting Methods

There are two ways to compare elements

Use the Comparable interface for objects that are instances of java.lang.Comparable

String, Date, all the wrapper classes for the primitive types

Objects are compared using the compareTo() method (see section 11.5)

This approach is referred to as natural order

The compareTo() returns

Negative integer if less than

Zero if equal

Positive integer is greater


Using treeset to sort elements in a set

Using TreeSet to Sort Elements in a Set

  • This example creates a hash set filled with strings and then creates a tree set for the same strings

  • The strings are sorted in the tree set using the compareTo()method in the Comparable interface

  • The example also creates a tree set of geometric objects

  • The geometric objects are sorted using the compareTo() method in the Comparator interface

TestTreeSet

Run

Listing 22.4


The comparator interface 1

The Comparator Interface (1)

Sometimes one wants to insert elements into a tree that may not be instances of java.lang.Comparableor one does not want to use the compareTo() method

Circles, squares, etc.

Since compare methods are different for different types of objects, one needs to define a generic compare method

It is then tailored for the specific object


The comparator interface 2

The Comparator Interface (2)

One defines a comparator to compare these elements

To do so, create a class that implements the java.util.Comparator interface

This interface is defined in the java.lang.package


The comparator interface 3

The Comparator Interface (3)

The Comparator interface has two methods

public int compare(Object element1, Object element2)

Returns a negative value if element1 is less than element2, a positive value if element1 is greater than element2, and zero if they are equal

public boolean equals(Object element)

Returns true if the specified object is also a comparator and imposes the same ordering as this comparator


Key comparison example

Key Comparison Example

  • Given keys 4 and 11

    • If the keys are integers

      • 4  11

    • If the keys are strings

      • 11  4


The comparator interface

The Comparator Interface

  • The following declares a Comparator for geometric objects

    • It implements Serializable

      • A Java object is serializableif its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable

      • To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object

      • Objects that can be written to an output stream

Listing 22.5

GeometricObjectComparator

37


Another comparator example

Another Comparator Example

/** Comparator using standard lexicographic order. */

public class Lexicographic<E extends Point2D> implements java.util.Comparator<E>

{

/** Compare two points (x and y coordinates)*/

public int compare(E a, E b) {

if (a.getX() != b.getX())

return b.getX() - a.getX();

else

return b.getY() - a.getY();

}

}


Using comparator to sort elements in a set

Using Comparator to Sort Elements in a Set

  • This program demonstrates how to sort elements in a tree set using the Comparator interface

  • This example creates a tree set of geometric objects

  • The geometric objects are sorted using the compare() method in the Comparator interface

Listing 22.6

TestTreeSetWithComparator

Run


Java collection concrete classes

Java Collection Concrete Classes

  • All concrete classes have at least two constructors

    • One is a no-argument constructor that constructs an empty class

    • The other constructs instances from a collection


Sorted sets1

Sorted Sets

  • If a sorted set is not needed, a hash set should be used

    • Takes less time to insert and remove elements in a hash set compared to a sorted set


The list interface 1

The List Interface (1)

  • A set stores non-duplicate elements

  • To allow duplicate elements to be stored in a collection, one needs to use a list

  • A list can not only store duplicate elements, but can also allow the user to specify where the element is stored

  • The user can access the element by index


The list interface 2

The List Interface (2)

The List interface extends Collection to defined an ordered collections where duplicates are allowed

The List interface adds position-oriented operations as well as a list iterator that enables one to traverse a list

43


The list interface 3

The List Interface (3)


The listiterator

The ListIterator

The listIterator() method returns an instance of the ListIterator

The ListIterator extends the Iterator interface to add bidirectional traversal of the list

45


The list iterator

The List Iterator


Arraylist

ArrayList

  • The ArrayList class is a concrete implementation of the List interface

    • If one needs to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection

    • An array is fixed once it is created

47


Java util arraylist

java.util.ArrayList


Linkedlist

LinkedList

  • The LinkedList class is a concrete implementations of the List interface

  • If an application requires the insertion or deletion of elements from any place in the list, one should choose LinkedList

    • This list can grow or shrink dynamically


Java util linkedlist

java.util.LinkedList


Using arraylist and linkedlist

Using ArrayList and LinkedList

  • This example creates an array list filled with numbers, and inserts new elements into the specified location in the list

  • The example also creates a linked list from the array list, inserts and removes the elements from the list

  • Finally, the example traverses the list forward and backward

See TestArrayAndLinkedList


The collections class

The Collections Class

  • One can use TreeSet to store sorted members in a set (there is no sorted list)

  • The Java Collections Framework provides static members within the Collections class that can be used to sort a list

    • It also contains various other methods (binary search, reverse, shuffle, copy, fill, max, min, disjoint, and frequency)

      • Static methods typically just access static variables


The collections class uml diagram

The Collections Class UML Diagram


Using the collections class

Using the Collections Class

  • This example demonstrates using the methods in the Collections class

  • The example creates a list, sorts it, and searches for an element

  • The example wraps the list into a synchronized and read-only list

Page 743

TestCollections


Test collection output

Test Collection Output

The initial list is [red, red, red]

After filling yellow, the list is [yellow, yellow, yellow]

After adding new elements, the list is

[yellow, yellow, yellow, white, black, orange]

After shuffling, the list is

[yellow, black, orange, yellow, yellow, white]

The minimum element in the list is black

The maximum element in the list is yellow

The sorted list is

[black, orange, white, yellow, yellow, yellow]

The search result for gray is -2

java.lang.UnsupportedOperationException

55


Performance of sets and list

Performance of Sets and List

  • To test the performance of sets and lists

SetListPerformanceTest example

Output is on page 746

56


The vector class 1

The Vector Class (1)

  • The Java Collections Framework was introduced with Java 2

  • Several data structures were supported prior to Java 2

  • Among them is the Vector class

  • This classes was redesigned to fit into the Java Collections Framework, but their old-style methods are retained for compatibility


The vector class 2

The Vector Class (2)

  • In Java 2, Vector is the same as ArrayList, except that Vector contains the synchronized methods for accessing and modifying the vector

  • Synchronizationmethods can prevent data corruption when a vector is accessed and modified by two or more threads concurrently

  • None of the new collection data structures introduced so far are synchronized

  • If synchronization is required, one can use the synchronized versions of the collection classes


The vector class 3

The Vector Class (3)

The Vector class implements the List interface

The addElement(Object element) method in the Vector class is the same as the add(Object element)method for the List interface except that addElement(Object element) is synchronized

59


The vector class uml

The Vector Class UML


Stacks

Stacks


Stacks1

Stacks

  • A data structure where addition and deletion of elements take place only at one end, called the top of the stack

    • A last in first out (LIFO) data structure

  • In a cafeteria the second tray, in a stack of trays, can be removed only if the first tray is removed


Applications of stacks

Applications of Stacks

  • Direct applications

    • Page-visited history in a Web browser

    • Undo sequence in a text editor

    • Chain of method calls in the Java Virtual Machine

  • Indirect applications

    • Auxiliary data structure for algorithms

    • Component of other data structures


Method stack in the jvm

Method Stack in the JVM

main() {int i = 5;func1(i);}

func1(int j) {int k;k = j+1;func2(k);}

func2(int m) {…}

  • The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack

  • When a method is called, the JVM pushes on the stack a frame containing

    • Local variables and return value

    • Program counter, keeping track of the statement being executed

  • When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack

func2

PC = 1 m = 6

func1

PC = 3 j = 5

k = 6

main

PC = 2 i = 5


The stack class 1

The Stack Class (1)

The Java Collections Framework was introduced with Java 2

Several data structures were supported prior to Java 2

Among them is the Stack class

This classes was redesigned to fit into the Java Collection Framework, but their old-style methods are retained for compatibility

65


The stack class 2

The Stack Class (2)

  • TheStackclass represents a last-in-first-out stack of objects. The elements are accessed only from the top of the stack

  • One can retrieve, insert, or remove an element from the top of the stack


The stack class 3

The Stack Class (3)

  • Built in class in java.util package

  • Stores generic objects

  • Provides various methods

    • pop(), push(), peek(), size (), empty()

  • Operations pop () and peek() cannot be performed if the stack is empty

    • EmptyStackException is thrown


The stack class

The Stack Class

68


Queues

Queues


Queues1

Queues

  • A queue is a first-in/first-out data structure

  • Elements are appended to the end of the queue and are removed from the beginning of the queue


Applications of queues

Applications of Queues

  • Direct applications

    • Waiting lists, bureaucracy

    • Access to shared resources (e.g., printer)

    • Multiprogramming

  • Indirect applications

    • Auxiliary data structure for algorithms

    • Component of other data structures


The queue interface

The Queue Interface


Java util queue

java.util.Queue

  • offer()– similar to add() method but preferred for queues

  • remove() and poll() are similar except the poll() returns a null and the remove() throws an exception if the queue is empty

  • peek() and element() are similar except the peek() returns a null and the element() throws an exception if the queue is empty


Deque

Deque

  • Deque supports element insertion and removal at both ends of a queue

    • Double ended queue

  • The Deque interface extends Queue

    • addFirst(e), removeFirst(), addlast(e), removeLast(), getFirst(), getLast()

  • The LinkedList class implements the Deque interface

See TestQueue example


Priority queues

Priority Queues

In a priority queue, elements are assigned priorities

When accessing elements, the element with the highest priority is removed first

75


Priority queues1

Priority Queues

  • Stores a collection of prioritized entries

    • Supports arbitrary element insertion

    • Supports removal of elements in order of priority

    • Element with first priority can be removed at any time

    • There is no concept of position

    • Are fundamentally different from position based data structures such as stacks, queues, lists, and trees which store elements at specific positions (often in a linear arrangement)


Applications of priority queues

Applications of Priority Queues

  • Standby flyers

  • Auctions

  • Stock market

    • Limit orders


Priority queue keys

Priority Queue Keys

  • An object that is assigned to an element as a specified attribute of the element which an order is defined

  • Used to identify the element

  • May and may not represent a property that the element did not originally process

  • Two distinct entries in a priority queue can have the same keys

  • Can be changed by an application

  • Often complex

    • Made up a several values


Total order relations

Total Order Relations

  • A priority queue needs a comparison rules, , that will never contradict itself

    • The rules must be a total order relation

      • Must be true for every pair of keys

      • Define linear ordering relationship


Total order relations properties

Total Order Relations Properties

  • Reflexive property k  k

  • Anti-symmetric property if k1k2and k2 k1k1= k2

  • Transitive property if k1 k2and k2 k3 k1 k3

  • Given that a finite collection there is a well defined kmin such that kmin k for all keys


Comparators

Comparators

  • A comparator encapsulates the action of comparing two objects according to a given total order relation

  • A generic priority queue uses an auxiliary comparator

    • The comparator is external to the keys being compared

  • When the priority queue needs to compare two keys, it uses its comparator


The priorityqueue class

The PriorityQueue Class

Listing 22. 10

PriorityQueueDemo

Run


Priority queue methods

Priority Queue Methods

  • By default, priority queues use Comparator interface

  • The element with the least value is assigned the highest priority (removed first)

    • Ties are broken arbitrarily

    • One can specify a different ordering in the constructor


  • Login