SlideShare a Scribd company logo
1 of 103
Object-oriented
programming
Outline
ī‚´ An Overview of the Java Collections Framework
ī‚´ Linked Lists
ī‚´ Sets
ī‚´ Maps
ī‚´ Stacks Queues and Priority Queues
ī‚´ Stack and Queue Applications
OBJECTIVES
ī‚´ To learn how to use the collection classes supplied in the
Java library
ī‚´ To use iterators to traverse collections
ī‚´ To choose appropriate collections for solving programming
problems
ī‚´ To study applications of stacks and queues
Page 3
Java Collections Framework
ī‚´ The Java Collections Framework is a collection of
interfaces and classes which helps in storing and
processing the data efficiently. This framework has several
useful classes which have tons of useful functions which
makes a programmer task super easy
Java Collections Framework
ī‚´ When you need to organize multiple objects in your
program, you can place them into a collection
ī‚´ The ArrayList class as an example. It is one of many
collection classes that the standard Java library supplies
ī‚´ Each interface type is implemented by one or more classes
Java Collections Framework
A collections framework is a unified architecture for representing
and manipulating collections.
ī‚´ Interfaces − These are abstract data types that represent
collections. Interfaces allow collections to be manipulated
independently of the details of their representation.
ī‚´ Implementations − These are the concrete implementations of
the collection interfaces.
ī‚´ Algorithms − Methods that perform useful computations,
(searching and sorting), on objects that implement collection
interfaces. Algorithms said to be polymorphic: the same
method can be used on many different implementations of the
appropriate collection interface.
Collections Framework hierarchy
Each collection
class
implements an
interface from a
hierarchy
Each class is
designed for a
specific type of
storage
Java Collections Framework
Java Collection Framework supports two
types of containers:
- collections: for storing a collection of
elements
- map: for storing key/value pairs
The collection interfaces
ī‚´ The Collection Interface
This enables you to work with groups of objects; it is at the
top of the collections hierarchy.
ī‚´ The List Interface
This extends Collection and an instance of List stores an
ordered collection of elements.
ī‚´ The Set
This extends Collection to handle sets, which must contain
unique elements.
ī‚´ The SortedSet
This extends Set to handle sorted sets.
The collection interfaces
ī‚´ The Map
This maps unique keys to values.
ī‚´ The Map.Entry
This describes an element (a key/value pair) in a map. This
is an inner class of Map.
ī‚´ The SortedMap
This extends Map so that the keys are maintained in an
ascending order.
ī‚´ Iterator
Iterator enables you to cycle through a collection, obtaining
or removing elements.
The collection interfaces
The Collection interface is the foundation upon which the
collections framework is built. It declares the core methods that
all collections will have.
Methods and Description:
ī‚´ boolean add(Object obj)
Adds obj to the invoking collection. Returns true if obj was
added to the collection. Returns false if obj is already a
member of the collection, or if the collection does not allow
duplicates.
ī‚´ boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns
true if the operation succeeds (i.e., the elements were added).
Otherwise, returns false.
The collection interfaces
ī‚´ void clear( )
Removes all elements from the invoking collection.
ī‚´ boolean contains(Object obj)
Returns true if obj is an element of the invoking collection. Otherwise, returns false.
ī‚´ boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. Otherwise, returns false.
ī‚´ boolean equals(Object obj)
Returns true if the invoking collection and obj are equal. Otherwise, returns false.
ī‚´ int hashCode( )
Returns the hash code for the invoking collection.
ī‚´ boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.
ī‚´ Iterator iterator( )
Returns an iterator for the invoking collection.
The collection interfaces
ī‚´ boolean remove(Object obj)
Removes one instance of obj from the invoking collection. Returns true if the element
was removed. Otherwise, returns false.
ī‚´ boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the collection
changed.
ī‚´ boolean retainAll(Collection c)
Removes all elements from the invoking collection except those in c. Returns true if the
collection changed.
ī‚´ int size( )
Returns the number of elements held in the invoking collection.
ī‚´ Object[ ] toArray( )
ī‚´ Returns an array that contains all the elements stored in the invoking collection. The
array elements are copies of the collection elements.
ī‚´ Object[ ] toArray(Object array[ ])
ī‚´ Returns an array containing only those collection elements whose type matches that of
array
The List Interface
The List interface extends Collection and declares
the behavior of a collection that stores a sequence
of elements.
ī‚´ Elements can be inserted or accessed by their position in
the list, using a zero-based index.
ī‚´ A list may contain duplicate elements.
Example
Lists and Sets
ī‚´ Ordered Lists
ī‚´ ArrayList
ī‚´ Stores a list of items in a dynamically sized array
ī‚´ LinkedList
ī‚´ Allows speedy insertion and removal of items from the list
Page 16
A list is a collection that maintains
the order of its elements.
Lists and Sets
ī‚´ Unordered Sets
ī‚´ HashSet
ī‚´ Uses hash tables to speed up finding, adding, and removing elements
ī‚´ TreeSet
ī‚´ Uses a binary tree to speed up finding, adding, and removing elements
Page 17
A set is an unordered collection
of unique elements.
Stacks and Queues
ī‚´Another way of gaining efficiency in a collection
is to reduce the number of operations available
ī‚´Two examples are:
ī‚´Stack
ī‚´Remembers the order of its elements, but it does not
allow you to insert elements in every position
ī‚´You can only add and remove elements at the top
ī‚´Queue
ī‚´Add items to one end (the tail)
ī‚´Remove them from the other end (the head)
ī‚´Example: A line of people waiting for a bank teller
Page 18
Maps
ī‚´A map stores keys, values, and the associations
between them
ī‚´Example:
ī‚´ Barcode keys and books
ī‚´Keys
ī‚´Provides an easy way to represent an object (such as a
numeric bar code)
ī‚´Values
ī‚´The actual object that is associated with the key
Page 19
A map keeps associations
between key and value objects.
The Collection Interface (1)
ī‚´List, Queue and Set are specialized interfaces
that inherit from the Collection interface
ī‚´All share the following commonly used methods
Page 20
The Collection Interface (2)
Page 21
15.2 Linked Lists
ī‚´Linked lists use references to maintain an ordered
lists of ‘nodes’
ī‚´The ‘head’ of the list references the first node
ī‚´Each node has a value and a reference to the next
node
ī‚´They can be used to implement
ī‚´ A List Interface
ī‚´ A Queue Interface
Page 22
Linked Lists Operations
ī‚´Efficient Operations
ī‚´Insertion of a node
ī‚´Find the elements it goes between
ī‚´Remap the references
ī‚´Removal of a node
ī‚´Find the element to remove
ī‚´Remap neighbor’s references
ī‚´Visiting all elements in order
ī‚´ Inefficient Operations
ī‚´ Random access
Page 23
Each instance variable is declared just
like other variables we have used.
LinkedList: Important Methods
Page 24
Generic Linked Lists
ī‚´The Collection Framework uses Generics
ī‚´Each list is declared with a type field in < > angle brackets
Page 25
LinkedList<String>
LinkedList<Employee>
LinkedList<String> employeeNames = . . .;
List Iterators
īą When traversing a LinkedList, use a ListIterator
ī‚§ Keeps track of where you are in the list.
īą Use an iterator to:
ī‚§ Access elements inside a linked list
ī‚§ Visit other than the first and the last nodes
Page 26
LinkedList<String> employeeNames = . . .;
ListIterator<String> iter = employeeNames.listIterator()
Using Iterators
ī‚´Think of an iterator as pointing between two
elements
Page 27
īą Note that the generic type for the listIterator
must match the generic type of the LinkedList
iterator.next();
iterator.add(“J”);
ListIterator<String> iter = myList.listIterator()
Iterator and ListIterator Methods
ī‚´Iterators allow you to move through a list easily
ī‚´Similar to an index variable for an array
Page 28
Iterators and Loops
ī‚´Iterators are often used in while and “for-each” loops
ī‚´hasNext returns true if there is a next element
ī‚´next returns a reference to the value of the next element
ī‚´Where is the iterator in the “for-next” loop?
ī‚´It is used ‘behind the scenes’
Page 29
while (iterator.hasNext())
{
String name = iterator.next();
// Do something with name
} for (String name : employeeNames)
{
// Do something with name
}
while (iterator.hasNext())
{
String name = iterator.next();
if (condition is true for name)
{
iterator.remove();
}
}
Adding and Removing with Iterators
ī‚´Adding
ī‚´A new node is added AFTER the Iterator
ī‚´The Iterator is moved past the new node
ī‚´Removing
ī‚´Removes the object that was returned with the last call to
next or previous
ī‚´It can be called only once after next or previous
ī‚´You cannot call it immediately after a call to add.
Page 30
iterator.add("Juliet");
If you call the remove
method improperly, it throws
an IllegalStateException.
ListDemo.java (1)
ī‚´Illustrates adding, removing and printing a list
Page 31
ListDemo.java (2)
Page 32
The Set Interface
ī‚´ A Set is a Collection that cannot contain duplicate elements.
It models the mathematical set abstraction.
ī‚´ The Set interface contains only methods inherited from
Collection and adds the restriction that duplicate elements
are prohibited.
ī‚´ Set has its implementation in various classes like HashSet,
TreeSet, LinkedHashSet.
Example
Sets
ī‚´ A set is an unordered collection
ī‚´ It does not support duplicate elements
ī‚´ The collection does not keep track of the order in which
elements have been added
ī‚´ Therefore, it can carry out its operations more efficiently than an
ordered collection
Page 35
The HashSet and TreeSet classes both
implement the Set interface.
Sets
ī‚´HashSet: Stores data in a Hash Table
ī‚´TreeSet: Stores data in a Binary Tree
ī‚´Both implementations arrange the set
elements so that finding, adding, and
removing elements is efficient
Page 36
Set implementations arrange the elements
so that they can locate them quickly
The SortedSet Interface
The SortedSet interface extends Set and declares
the behavior of a set sorted in an ascending order.
SortedSet have its implementation in various
classes like TreeSet.
Example
Hash Table Concept
ī‚´Set elements are grouped into smaller collections
of elements that share the same characteristic
ī‚´It is usually based on the result of a mathematical
calculation on the contents that results in an integer
value
ī‚´In order to be stored in a hash table, elements must
have a method to compute their integer values
Page 39
100
101
102
hashCode
ī‚´ The method is called hashCode
ī‚´ If multiple elements have the same hash code, they are stored in a
Linked list
ī‚´ The elements must also have an equals method for checking
whether an element equals another like:
ī‚´ String, Integer, Point, Rectangle, Color, and all collection classes
Page 40
Set<String> names = new HashSet<String>();
Tree Concept
ī‚´ Set elements are kept in sorted order
ī‚´ Nodes are not arranged in a linear sequence
but in a tree shape
ī‚´ In order to use a TreeSet, it must be possible to compare the elements and determine
which one is “larger”
Page 41
TreeSet
ī‚´Use TreeSet for classes that implement
the Comparable interface
ī‚´String and Integer, for example
ī‚´The nodes are arranged in a ‘tree’
fashion so that each ‘parent’ node has
up to two child nodes.
ī‚´The node to the left always has a ‘smaller’
value
ī‚´The node to the right always has a ‘larger’
value
Page 42
Set<String> names = new TreeSet<String>();
Iterators and Sets
ī‚´Iterators are also used when processing sets
ī‚´hasNext returns true if there is a next element
ī‚´next returns a reference to the value of the next element
ī‚´add via the iterator is not supported for TreeSet and HashSet
ī‚´Note that the elements are not visited in the order in which you
inserted them.
ī‚´They are visited in the order in which the set keeps them:
ī‚´Seemingly random order for a HashSet
ī‚´Sorted order for a TreeSet
Page 43
Iterator<String> iter = names.iterator();
while (iter.hasNext())
{
String name = iter.next();
// Do something with name
}
for (String name : names)
{
// Do something with name
}
Working With Sets (1)
Page 44
Working With Sets (2)
Page 45
SpellCheck.java (1)
Page 46
SpellCheck.java (2)
Page 47
Programming Tip
ī‚´Use Interface References to Manipulate Data
Structures
ī‚´It is considered good style to store a reference to a
HashSet or TreeSet in a variable of type Set.
ī‚´This way, you have to change only one line if you decide to use
a TreeSet instead.
Page 48
Set<String> words = new HashSet<String>();
Programming Tip (continued)
ī‚´Unfortunately the same is not true of the
ArrayList, LinkedList and List
classes
ī‚´ The get and set methods for random access are very inefficient
ī‚´Also, if a method can operate on arbitrary
collections, use the Collection interface
type for the parameter:
Page 49
public static void removeLongWords(Collection<String> words)
The Map Interface
ī‚´ The Map interface maps unique keys to values. A key is an
object that you use to retrieve a value at a later date.
ī‚´ Given a key and a value, you can store the value in a Map
object. After the value is stored, you can retrieve it by using
its key.
ī‚´ Map has its implementation in various classes like
HashMap.
Example
Maps
ī‚´A map allows you to associate elements from a key
set with elements from a value collection.
ī‚´ The HashMap and TreeMap classes both implement the Map interface.
ī‚´ Use a map to look up objects by using a key.
Page 52
Maps
Page 53
Map<String, Color> favoriteColors = new HashMap<String, Color>();
Key Value
Key Value
Working with Maps (Table 5)
Page 54
Key Value Pairs in Maps
ī‚´ Each key is associated with a value
Page 55
Map<String, Color> favoriteColors = new HashMap<String, Color>();
favoriteColors.put("Juliet", Color.RED);
favoriteColors.put(“Romeo", Color.GREEN);
Color julietsFavoriteColor = favoriteColors.get("Juliet");
favoriteColors.remove("Juliet");
Iterating through Maps
ī‚´To iterate through the map, use a keySet to get the list
of keys:
Page 56
Set<String> keySet = m.keySet();
for (String key : keySet)
{
Color value = m.get(key);
System.out.println(key + "->" + value);
}
To find all values in a map,
iterate through the key set
and find the values that
correspond to the keys.
MapDemo.java
Page 57
The Map.Entry Interface
ī‚´ The Map.Entry interface enables you to work with a map
entry.
ī‚´ The entrySet( ) method declared by the Map interface
returns a Set containing the map entries. Each of these set
elements is a Map.Entry object.
Example
The SortedMap Interface
The SortedMap interface extends Map. It ensures
that the entries are maintained in an ascending key
order.
SortedMap has its implementation in various
classes like TreeMap.
Example
Steps to Choosing a Collection
1) Determine how you access values
ī‚´Values are accessed by an integer position. Use an
ArrayList
ī‚´Go to Step 2, then stop
ī‚´Values are accessed by a key that is not a part of the
object
ī‚´Use a Map.
ī‚´It doesn’t matter. Values are always accessed “in bulk”,
by traversing the collection and doing something with
each value
2) Determine the element types or key/value types
ī‚´For a List or Set, a single type
ī‚´For a Map, the key type and the value type
Page 62
Steps to Choosing a Collection
3) Determine whether element or key order
matters
ī‚´ Elements or keys must be sorted
ī‚´ Use a TreeSet or TreeMap. Go to Step 6
ī‚´ Elements must be in the same order in which they
were inserted
ī‚´ Your choice is now narrowed down to a LinkedList or
an ArrayList
ī‚´ It doesn’t matter
ī‚´ If you chose a map in Step 1, use a HashMap and go to
Step 5
Page 63
Steps to Choosing a Collection
4) For a collection, determine which operations must be fast
ī‚´ Finding elements must be fast
ī‚´ Use a HashSet and go to Step 5
ī‚´ Adding and removing elements at the beginning or the middle must
be fast
ī‚´ Use a LinkedList
ī‚´ You only insert at the end, or you collect so few elements that you
aren’t concerned about speed
ī‚´ Use an ArrayList.
Page 64
Steps to Choosing a Collection
5) For hash sets and maps, decide if you
need to implement the equals and
hashCode methods
ī‚´If your elements do not support them, you
must implement them yourself.
6) If you use a tree, decide whether to
supply a comparator
ī‚´If your element class does not provide it,
implement the Comparable interface for your
element class
Page 65
Special Topic: Hash Functions
ī‚´ Hashing can be used to find elements in a set data structure quickly,
without making a linear search through all elements.
ī‚´ A hashCode method computes and returns an integer value: the hash
code.
ī‚´ Should be likely to yield different hash codes
ī‚´ Because hashing is so important, the Object class has a hashCode method
that computes the hash code of any object x.
Page 66
int h = x.hashCode();
Computing Hash Codes
ī‚´ To put objects of a given class into a HashSet or use
the objects as keys in a HashMap, the class should
override the default hashCode method.
ī‚´ A good hashCode method should work such that
different objects are likely to have different hash codes.
ī‚´ It should also be efficient
ī‚´ A simple example for a String might be:
Page 67
int h = 0;
for (int i = 0; i < s.length(); i++)
{
h = h + s.charAt(i);
}
Computing Hash Codes
ī‚´But Strings that are permutations of
another (such as "eat" and "tea") would
all have the same hash code
ī‚´Better:
ī‚´ From the Java Library!
Page 68
final int HASH_MULTIPLIER = 31;
int h = 0;
for (int i = 0; i < s.length(); i++)
{
h = HASH_MULTIPLIER * h + s.charAt(i);
}
Sample Strings and HashCodes
ī‚´ The String class implements a good example of a
hashCode method
ī‚´ It is possible for two or more distinct objects to have the
same hash code: This is called a collision
ī‚´A hashCode function should minimizes collisions
Page 69
Computing Object Hash Codes
ī‚´ You should have a good hashCode method for your
own objects to store them efficiently
ī‚´ Override hashCode methods in your own classes by
combining the hash codes for the instance variables
ī‚´ Then combine the hash codes using a prime-number
hash multiplier:
Page 70
public int hashCode()
{
int h1 = name.hashCode();
int h2 = new Double(area).hashCode();
. . .
final int HASH_MULTIPLIER = 29;
int h = HASH_MULTIPLIER * h1 + h2;
return h;
}
hashCode and equals methods
ī‚´hashCode methods should be compatible with
equals methods
ī‚´If two objects are equal, their hashCodes should match
ī‚´a hashCode method should use all instance variables
ī‚´The hashCode method of the Object class uses the
memory location of the object, not the contents
Page 71
hashCode and equals
methods
ī‚´Do not mix Object class hashCode or equals
methods with your own:
ī‚´Use an existing class such as String. Its
hashCode and equals methods have already
been implemented to work correctly.
ī‚´Implement both hashCode and equals.
ī‚´ Derive the hash code from the instance variables that
the equals method compares, so that equal objects
have the same hash code
ī‚´Implement neither hashCode nor equals. Then
only identical objects are considered to be equal
Page 72
15.5 Stacks, Queues and Priority Queues
ī‚´Queues and Stacks are specialized lists
ī‚´Only allow adding and removing from the ends
Page 73
Insert At Remove At Operation
Stack Start(top) Start(top) List in, first out (LIFO)
Queue End (tail) Start (head) First in, first out (FIFO)
Priority Queue By Priority Highest
Priority
(Lowest #)
Prioritized list of tasks
Stacks, Queues and Priority
Queues
ī‚´Stacks are used for undo features
(most recent first)
ī‚´Queues are like lines at the bank
or store
ī‚´Priority Queues remove lowest
number first
Page 74
Working with Stacks
Page 75
Stack Example
ī‚´The Java library provides a Stack class that
implements the abstract stack type’s push and
pop operations.
ī‚´The Stack is not technically part of the Collections
framework, but uses generic type parameters
Page 76
Stack<String> s = new Stack<String>();
s.push("A");
s.push("B");
s.push("C");
// The following loop prints C, B, and A
while (s.size() > 0)
{
System.out.println(s.pop());
}
The stack class
provides a size method
Queues and Priority Queues
Page 77
Priority Queues
ī‚´A priority Queue collects elements, each of which
has a priority
ī‚´Example: a collection of work requests, some of which
may be more urgent than others
ī‚´It is NOT a FIFO Queue
ī‚´Lowest value priority (1) will be removed first
Page 78
PriorityQueue<WorkOrder> q = new PriorityQueue<WorkOrder>();
q.add(new WorkOrder(3, "Shampoo carpets"));
q.add(new WorkOrder(1, "Fix broken sink"));
q.add(new WorkOrder(2, "Order cleaning supplies"));
WorkOrder next = q.remove(); // removes “Fix broken sink”
15.6 Stack and Queue Applications
ī‚´ Balancing Parenthesis
ī‚´Section 2.5, showed how to balance parenthesis by
adding 1 for each left ( and subtracting for each right )
ī‚´A stack can be used to keep track of ‘depth’:
When you see an opening parenthesis, push it on the stack.
When you see a closing parenthesis, pop the stack.
If the opening and closing parentheses don’t match
The parentheses are unbalanced. Exit.
If at the end the stack is empty
The parentheses are balanced.
Else
The parentheses are not balanced.
Page 79
Using a Stack (Example)
ī‚´ Here is a walkthrough of the sample expression
ī‚´ We will use the mathematical version (three types of parenthesis)
Page 80
Reverse Polish Expressions
ī‚´ The first handheld calculator used a notation that was easily implemented with a
stack: Reverse Polish
ī‚´ No parenthesis required if youâ€Ļ
ī‚´Input both operands first, then the operator:
Page 81
Algebra Reverse Polish
(3 + 4) x 5 3 4 + 5 x
(3 + 4) x (5 + 6) 3 4 + 5 6 + x
Reverse Polish Expressions
If you read a number
Push it on the stack.
Else if you read an operand
Pop two values off the stack.
Combine the values with the operand.
Push the result back onto the stack.
Else if there is no more input
Pop and display the result.
Page 82
Reverse Polish Calculator
ī‚´ Walkthrough with 3 4 5 + x
Page 83
Calculator.java (1)
Page 84
Calculator.java (2)
Page 85
Evaluating Algebraic Expressions
ī‚´Can be done with two stacks:
1) Numbers
2) Operators
ī‚´First Example: 3 + 4
Page 86
Expression Example 2
ī‚´Second Example: 3 x 4 + 5
ī‚´Must use precedence (multiply before adding)
Page 87
Precedence and Expressions (1)
ī‚´Third Example: 3 + 4 x 5
ī‚´Keep operators on the stack until they are ready to be
evaluated
Page 88
Precedence and Expressions (2)
ī‚´Third Example: 3 + 4 x 5
ī‚´Evaluate top 2 numbers with top operator
ī‚´Store result on top of stack
ī‚´Evaluate until operator stack is empty
Page 89
Expressions with Parenthesis (1)
ī‚´Fourth Example: 3 x ( 4 + 5 )
ī‚´If (, don’t evaluate. If ), evaluate
Page 90
Expressions with Parenthesis (2)
ī‚´Fourth Example: 3 x ( 4 + 5 )
ī‚´Don’t put ) on stack – evaluate now
ī‚´Ignore (
Page 91
Precedence Algorithm
If you read a number
Push it on the number stack.
Else if you read a (
Push it on the operator stack.
Else if you read an operator op
While the top of the stack has a higher precedence than op
Evaluate the top.
Push op on the operator stack.
Else if you read a )
While the top of the stack is not a (
Evaluate the top.
Pop the ).
Else if there is no more input
While the operator stack is not empty
Evaluate the top.
Page 92
Evaluate the Top:
Pop two numbers off the
number stack.
Pop an operator off the
operator stack.
Combine the numbers with
that operator.
Push the result on the
number stack.
Backtracking (1)
ī‚´Uses a stack to solve a maze
ī‚´Stack current location, arrow
for each possible path
1. We pop off the topmost one,
traveling north from (3, 4).
Following this path leads to
position (1, 4).
2. We now push two choices
on the stack, going west or
east.
Page 93
Backtracking (2)
3. Pop off (1, 4) east. It is a
dead end.
4. Pop off (1, 4) west. It is a
dead end.
5. Now we pop off the path
from (3, 4) going east. That
too is a dead end.
This leaves us with (3, 4) south
and (3, 4) west to try
Page 94
Backtracking (3)
6. Next is the path from (3, 4)
going south. At (5, 4), it comes
to an intersection. Both choices
are pushed on the stack.
7. (5, 4) south is a dead end.
8. (5, 4) west is a dead end.
9. Finally, the path from (3, 4)
going west leads to an exit
Page 95
Maze Solving Pseudocode
Push all paths from the point on which you are
standing on a stack.
While the stack is not empty
Pop a path from the stack.
Follow the path until you reach an exit,
intersection, or dead end.
If you found an exit
Congratulations!
Else if you found an intersection
Push all paths meeting at the intersection, except the current one,
onto the stack.
Page 96
Summary: Collections
ī‚´A collection groups together elements
and allows them to be retrieved later
ī‚´A list is a collection that remembers the
order of its elements
ī‚´A set is an unordered collection of unique
elements
ī‚´A map keeps associations between key
and value objects
Page 97
Summary: Linked Lists
ī‚´A linked list consists of a number of nodes, each of
which has a reference to the next node
ī‚´Adding and removing elements in the middle of a linked
list is efficient
ī‚´Visiting the elements of a linked list in sequential order
is efficient, but random access is not
ī‚´You use a list iterator to access elements of a linked list
Page 98
Summary: Choosing a Set
ī‚´ The HashSet and TreeSet classes both implement the Set
interface.
ī‚´ Set implementations arrange the elements so that they can
locate them quickly.
ī‚´ You can form hash sets holding objects of type String,
Integer, Double, Point, Rectangle, or Color.
ī‚´ You can form tree sets for any class that implements the
Comparable interface, such as String or Integer.
ī‚´ Sets don’t have duplicates. Adding a duplicate of an element
that is already present is silently ignored.
ī‚´ A set iterator visits the elements in the order in which the set
implementation keeps them.
ī‚´ You cannot add an element to a set at an iterator position.
Page 99
Summary: Maps
ī‚´ Maps associate keys with values
ī‚´ The HashMap and TreeMap classes both implement the Map interface
ī‚´ To find all keys and values in a Map, iterate through the key set and find
the values that correspond to the keys
ī‚´ A hash function computes an integer value from an object.
ī‚´ A good hash function minimizes collisions—identical hash codes for
different objects.
ī‚´ Override hashCode methods in your own classes by combining the hash
codes for the instance variables.
ī‚´ A class’s hashCode method must be compatible with its equals method.
Page 100
Summary: Stacks and Queues
ī‚´A stack is a collection of elements with
“last-in, first-out” retrieval.
ī‚´A queue is a collection of elements with
“first-in, first-out” retrieval.
ī‚´When removing an element from a priority
queue, the element with the most urgent
priority is retrieved.
Page 101
Summary: Problem Solving
ī‚´A stack can be used to check whether parentheses in
an expression are balanced.
ī‚´Use a stack to evaluate expressions in reverse Polish
notation.
ī‚´Using two stacks, you can evaluate expressions in
standard algebraic notation.
ī‚´Use a stack to remember choices you haven’t yet
made so that you can backtrack to them.
Page 102
Useful links
ī‚´ https://beginnersbook.com/java-collections-tutorials/

More Related Content

Similar to oop lecture framework,list,maps,collection

C# Collection classes
C# Collection classesC# Collection classes
C# Collection classesMohitKumar1985
 
Java collections
Java collectionsJava collections
Java collectionsHamid Ghorbani
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
List in java
List in javaList in java
List in javanitin kumar
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptxSoniaKapoor56
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
collections
collectionscollections
collectionsjaveed_mhd
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections frameworkRavi Chythanya
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java NotesShalabh Chaudhary
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40bhawna sharma
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )charan kumar
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and InformationSoftNutx
 
Scala collection
Scala collectionScala collection
Scala collectionKnoldus Inc.
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 

Similar to oop lecture framework,list,maps,collection (20)

C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
 
Java collections
Java collectionsJava collections
Java collections
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Ch03
Ch03Ch03
Ch03
 
List in java
List in javaList in java
List in java
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java.util
Java.utilJava.util
Java.util
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
collections
collectionscollections
collections
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Scala collection
Scala collectionScala collection
Scala collection
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 

Recently uploaded

VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneCall girls in Ahmedabad High profile
 
Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝soniya singh
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of indiaimessage0108
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneRussian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneCall girls in Ahmedabad High profile
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxellan12
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
Call Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on Deliverybabeytanya
 
象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdf
象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdf象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdf
象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdfkeithzhangding
 
✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 

Recently uploaded (20)

VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
 
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi đŸ’¯Call Us 🔝8264348440🔝
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of india
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi đŸĢĻ HOT AND SEXY VVIP 🍎 SERVICE
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service ThaneRussian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
Russian Call Girls Thane Swara 8617697112 Independent Escort Service Thane
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Call Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤ī¸ 9920874524 👈 Cash on Delivery
 
象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdf
象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdf象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdf
象限į­–į•ĨīŧšGoogle Workspace 与 Microsoft 365 å¯šä¸šåŠĄįš„åŊąå“ .pdf
 
✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂ī¸ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 

oop lecture framework,list,maps,collection

  • 2. Outline ī‚´ An Overview of the Java Collections Framework ī‚´ Linked Lists ī‚´ Sets ī‚´ Maps ī‚´ Stacks Queues and Priority Queues ī‚´ Stack and Queue Applications
  • 3. OBJECTIVES ī‚´ To learn how to use the collection classes supplied in the Java library ī‚´ To use iterators to traverse collections ī‚´ To choose appropriate collections for solving programming problems ī‚´ To study applications of stacks and queues Page 3
  • 4. Java Collections Framework ī‚´ The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy
  • 5. Java Collections Framework ī‚´ When you need to organize multiple objects in your program, you can place them into a collection ī‚´ The ArrayList class as an example. It is one of many collection classes that the standard Java library supplies ī‚´ Each interface type is implemented by one or more classes
  • 6. Java Collections Framework A collections framework is a unified architecture for representing and manipulating collections. ī‚´ Interfaces − These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. ī‚´ Implementations − These are the concrete implementations of the collection interfaces. ī‚´ Algorithms − Methods that perform useful computations, (searching and sorting), on objects that implement collection interfaces. Algorithms said to be polymorphic: the same method can be used on many different implementations of the appropriate collection interface.
  • 7. Collections Framework hierarchy Each collection class implements an interface from a hierarchy Each class is designed for a specific type of storage
  • 8. Java Collections Framework Java Collection Framework supports two types of containers: - collections: for storing a collection of elements - map: for storing key/value pairs
  • 9. The collection interfaces ī‚´ The Collection Interface This enables you to work with groups of objects; it is at the top of the collections hierarchy. ī‚´ The List Interface This extends Collection and an instance of List stores an ordered collection of elements. ī‚´ The Set This extends Collection to handle sets, which must contain unique elements. ī‚´ The SortedSet This extends Set to handle sorted sets.
  • 10. The collection interfaces ī‚´ The Map This maps unique keys to values. ī‚´ The Map.Entry This describes an element (a key/value pair) in a map. This is an inner class of Map. ī‚´ The SortedMap This extends Map so that the keys are maintained in an ascending order. ī‚´ Iterator Iterator enables you to cycle through a collection, obtaining or removing elements.
  • 11. The collection interfaces The Collection interface is the foundation upon which the collections framework is built. It declares the core methods that all collections will have. Methods and Description: ī‚´ boolean add(Object obj) Adds obj to the invoking collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates. ī‚´ boolean addAll(Collection c) Adds all the elements of c to the invoking collection. Returns true if the operation succeeds (i.e., the elements were added). Otherwise, returns false.
  • 12. The collection interfaces ī‚´ void clear( ) Removes all elements from the invoking collection. ī‚´ boolean contains(Object obj) Returns true if obj is an element of the invoking collection. Otherwise, returns false. ī‚´ boolean containsAll(Collection c) Returns true if the invoking collection contains all elements of c. Otherwise, returns false. ī‚´ boolean equals(Object obj) Returns true if the invoking collection and obj are equal. Otherwise, returns false. ī‚´ int hashCode( ) Returns the hash code for the invoking collection. ī‚´ boolean isEmpty( ) Returns true if the invoking collection is empty. Otherwise, returns false. ī‚´ Iterator iterator( ) Returns an iterator for the invoking collection.
  • 13. The collection interfaces ī‚´ boolean remove(Object obj) Removes one instance of obj from the invoking collection. Returns true if the element was removed. Otherwise, returns false. ī‚´ boolean removeAll(Collection c) Removes all elements of c from the invoking collection. Returns true if the collection changed. ī‚´ boolean retainAll(Collection c) Removes all elements from the invoking collection except those in c. Returns true if the collection changed. ī‚´ int size( ) Returns the number of elements held in the invoking collection. ī‚´ Object[ ] toArray( ) ī‚´ Returns an array that contains all the elements stored in the invoking collection. The array elements are copies of the collection elements. ī‚´ Object[ ] toArray(Object array[ ]) ī‚´ Returns an array containing only those collection elements whose type matches that of array
  • 14. The List Interface The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. ī‚´ Elements can be inserted or accessed by their position in the list, using a zero-based index. ī‚´ A list may contain duplicate elements.
  • 16. Lists and Sets ī‚´ Ordered Lists ī‚´ ArrayList ī‚´ Stores a list of items in a dynamically sized array ī‚´ LinkedList ī‚´ Allows speedy insertion and removal of items from the list Page 16 A list is a collection that maintains the order of its elements.
  • 17. Lists and Sets ī‚´ Unordered Sets ī‚´ HashSet ī‚´ Uses hash tables to speed up finding, adding, and removing elements ī‚´ TreeSet ī‚´ Uses a binary tree to speed up finding, adding, and removing elements Page 17 A set is an unordered collection of unique elements.
  • 18. Stacks and Queues ī‚´Another way of gaining efficiency in a collection is to reduce the number of operations available ī‚´Two examples are: ī‚´Stack ī‚´Remembers the order of its elements, but it does not allow you to insert elements in every position ī‚´You can only add and remove elements at the top ī‚´Queue ī‚´Add items to one end (the tail) ī‚´Remove them from the other end (the head) ī‚´Example: A line of people waiting for a bank teller Page 18
  • 19. Maps ī‚´A map stores keys, values, and the associations between them ī‚´Example: ī‚´ Barcode keys and books ī‚´Keys ī‚´Provides an easy way to represent an object (such as a numeric bar code) ī‚´Values ī‚´The actual object that is associated with the key Page 19 A map keeps associations between key and value objects.
  • 20. The Collection Interface (1) ī‚´List, Queue and Set are specialized interfaces that inherit from the Collection interface ī‚´All share the following commonly used methods Page 20
  • 22. 15.2 Linked Lists ī‚´Linked lists use references to maintain an ordered lists of ‘nodes’ ī‚´The ‘head’ of the list references the first node ī‚´Each node has a value and a reference to the next node ī‚´They can be used to implement ī‚´ A List Interface ī‚´ A Queue Interface Page 22
  • 23. Linked Lists Operations ī‚´Efficient Operations ī‚´Insertion of a node ī‚´Find the elements it goes between ī‚´Remap the references ī‚´Removal of a node ī‚´Find the element to remove ī‚´Remap neighbor’s references ī‚´Visiting all elements in order ī‚´ Inefficient Operations ī‚´ Random access Page 23 Each instance variable is declared just like other variables we have used.
  • 25. Generic Linked Lists ī‚´The Collection Framework uses Generics ī‚´Each list is declared with a type field in < > angle brackets Page 25 LinkedList<String> LinkedList<Employee> LinkedList<String> employeeNames = . . .;
  • 26. List Iterators īą When traversing a LinkedList, use a ListIterator ī‚§ Keeps track of where you are in the list. īą Use an iterator to: ī‚§ Access elements inside a linked list ī‚§ Visit other than the first and the last nodes Page 26 LinkedList<String> employeeNames = . . .; ListIterator<String> iter = employeeNames.listIterator()
  • 27. Using Iterators ī‚´Think of an iterator as pointing between two elements Page 27 īą Note that the generic type for the listIterator must match the generic type of the LinkedList iterator.next(); iterator.add(“J”); ListIterator<String> iter = myList.listIterator()
  • 28. Iterator and ListIterator Methods ī‚´Iterators allow you to move through a list easily ī‚´Similar to an index variable for an array Page 28
  • 29. Iterators and Loops ī‚´Iterators are often used in while and “for-each” loops ī‚´hasNext returns true if there is a next element ī‚´next returns a reference to the value of the next element ī‚´Where is the iterator in the “for-next” loop? ī‚´It is used ‘behind the scenes’ Page 29 while (iterator.hasNext()) { String name = iterator.next(); // Do something with name } for (String name : employeeNames) { // Do something with name }
  • 30. while (iterator.hasNext()) { String name = iterator.next(); if (condition is true for name) { iterator.remove(); } } Adding and Removing with Iterators ī‚´Adding ī‚´A new node is added AFTER the Iterator ī‚´The Iterator is moved past the new node ī‚´Removing ī‚´Removes the object that was returned with the last call to next or previous ī‚´It can be called only once after next or previous ī‚´You cannot call it immediately after a call to add. Page 30 iterator.add("Juliet"); If you call the remove method improperly, it throws an IllegalStateException.
  • 31. ListDemo.java (1) ī‚´Illustrates adding, removing and printing a list Page 31
  • 33. The Set Interface ī‚´ A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. ī‚´ The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. ī‚´ Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet.
  • 35. Sets ī‚´ A set is an unordered collection ī‚´ It does not support duplicate elements ī‚´ The collection does not keep track of the order in which elements have been added ī‚´ Therefore, it can carry out its operations more efficiently than an ordered collection Page 35 The HashSet and TreeSet classes both implement the Set interface.
  • 36. Sets ī‚´HashSet: Stores data in a Hash Table ī‚´TreeSet: Stores data in a Binary Tree ī‚´Both implementations arrange the set elements so that finding, adding, and removing elements is efficient Page 36 Set implementations arrange the elements so that they can locate them quickly
  • 37. The SortedSet Interface The SortedSet interface extends Set and declares the behavior of a set sorted in an ascending order. SortedSet have its implementation in various classes like TreeSet.
  • 39. Hash Table Concept ī‚´Set elements are grouped into smaller collections of elements that share the same characteristic ī‚´It is usually based on the result of a mathematical calculation on the contents that results in an integer value ī‚´In order to be stored in a hash table, elements must have a method to compute their integer values Page 39 100 101 102
  • 40. hashCode ī‚´ The method is called hashCode ī‚´ If multiple elements have the same hash code, they are stored in a Linked list ī‚´ The elements must also have an equals method for checking whether an element equals another like: ī‚´ String, Integer, Point, Rectangle, Color, and all collection classes Page 40 Set<String> names = new HashSet<String>();
  • 41. Tree Concept ī‚´ Set elements are kept in sorted order ī‚´ Nodes are not arranged in a linear sequence but in a tree shape ī‚´ In order to use a TreeSet, it must be possible to compare the elements and determine which one is “larger” Page 41
  • 42. TreeSet ī‚´Use TreeSet for classes that implement the Comparable interface ī‚´String and Integer, for example ī‚´The nodes are arranged in a ‘tree’ fashion so that each ‘parent’ node has up to two child nodes. ī‚´The node to the left always has a ‘smaller’ value ī‚´The node to the right always has a ‘larger’ value Page 42 Set<String> names = new TreeSet<String>();
  • 43. Iterators and Sets ī‚´Iterators are also used when processing sets ī‚´hasNext returns true if there is a next element ī‚´next returns a reference to the value of the next element ī‚´add via the iterator is not supported for TreeSet and HashSet ī‚´Note that the elements are not visited in the order in which you inserted them. ī‚´They are visited in the order in which the set keeps them: ī‚´Seemingly random order for a HashSet ī‚´Sorted order for a TreeSet Page 43 Iterator<String> iter = names.iterator(); while (iter.hasNext()) { String name = iter.next(); // Do something with name } for (String name : names) { // Do something with name }
  • 44. Working With Sets (1) Page 44
  • 45. Working With Sets (2) Page 45
  • 48. Programming Tip ī‚´Use Interface References to Manipulate Data Structures ī‚´It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set. ī‚´This way, you have to change only one line if you decide to use a TreeSet instead. Page 48 Set<String> words = new HashSet<String>();
  • 49. Programming Tip (continued) ī‚´Unfortunately the same is not true of the ArrayList, LinkedList and List classes ī‚´ The get and set methods for random access are very inefficient ī‚´Also, if a method can operate on arbitrary collections, use the Collection interface type for the parameter: Page 49 public static void removeLongWords(Collection<String> words)
  • 50. The Map Interface ī‚´ The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. ī‚´ Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. ī‚´ Map has its implementation in various classes like HashMap.
  • 52. Maps ī‚´A map allows you to associate elements from a key set with elements from a value collection. ī‚´ The HashMap and TreeMap classes both implement the Map interface. ī‚´ Use a map to look up objects by using a key. Page 52
  • 53. Maps Page 53 Map<String, Color> favoriteColors = new HashMap<String, Color>(); Key Value Key Value
  • 54. Working with Maps (Table 5) Page 54
  • 55. Key Value Pairs in Maps ī‚´ Each key is associated with a value Page 55 Map<String, Color> favoriteColors = new HashMap<String, Color>(); favoriteColors.put("Juliet", Color.RED); favoriteColors.put(“Romeo", Color.GREEN); Color julietsFavoriteColor = favoriteColors.get("Juliet"); favoriteColors.remove("Juliet");
  • 56. Iterating through Maps ī‚´To iterate through the map, use a keySet to get the list of keys: Page 56 Set<String> keySet = m.keySet(); for (String key : keySet) { Color value = m.get(key); System.out.println(key + "->" + value); } To find all values in a map, iterate through the key set and find the values that correspond to the keys.
  • 58. The Map.Entry Interface ī‚´ The Map.Entry interface enables you to work with a map entry. ī‚´ The entrySet( ) method declared by the Map interface returns a Set containing the map entries. Each of these set elements is a Map.Entry object.
  • 60. The SortedMap Interface The SortedMap interface extends Map. It ensures that the entries are maintained in an ascending key order. SortedMap has its implementation in various classes like TreeMap.
  • 62. Steps to Choosing a Collection 1) Determine how you access values ī‚´Values are accessed by an integer position. Use an ArrayList ī‚´Go to Step 2, then stop ī‚´Values are accessed by a key that is not a part of the object ī‚´Use a Map. ī‚´It doesn’t matter. Values are always accessed “in bulk”, by traversing the collection and doing something with each value 2) Determine the element types or key/value types ī‚´For a List or Set, a single type ī‚´For a Map, the key type and the value type Page 62
  • 63. Steps to Choosing a Collection 3) Determine whether element or key order matters ī‚´ Elements or keys must be sorted ī‚´ Use a TreeSet or TreeMap. Go to Step 6 ī‚´ Elements must be in the same order in which they were inserted ī‚´ Your choice is now narrowed down to a LinkedList or an ArrayList ī‚´ It doesn’t matter ī‚´ If you chose a map in Step 1, use a HashMap and go to Step 5 Page 63
  • 64. Steps to Choosing a Collection 4) For a collection, determine which operations must be fast ī‚´ Finding elements must be fast ī‚´ Use a HashSet and go to Step 5 ī‚´ Adding and removing elements at the beginning or the middle must be fast ī‚´ Use a LinkedList ī‚´ You only insert at the end, or you collect so few elements that you aren’t concerned about speed ī‚´ Use an ArrayList. Page 64
  • 65. Steps to Choosing a Collection 5) For hash sets and maps, decide if you need to implement the equals and hashCode methods ī‚´If your elements do not support them, you must implement them yourself. 6) If you use a tree, decide whether to supply a comparator ī‚´If your element class does not provide it, implement the Comparable interface for your element class Page 65
  • 66. Special Topic: Hash Functions ī‚´ Hashing can be used to find elements in a set data structure quickly, without making a linear search through all elements. ī‚´ A hashCode method computes and returns an integer value: the hash code. ī‚´ Should be likely to yield different hash codes ī‚´ Because hashing is so important, the Object class has a hashCode method that computes the hash code of any object x. Page 66 int h = x.hashCode();
  • 67. Computing Hash Codes ī‚´ To put objects of a given class into a HashSet or use the objects as keys in a HashMap, the class should override the default hashCode method. ī‚´ A good hashCode method should work such that different objects are likely to have different hash codes. ī‚´ It should also be efficient ī‚´ A simple example for a String might be: Page 67 int h = 0; for (int i = 0; i < s.length(); i++) { h = h + s.charAt(i); }
  • 68. Computing Hash Codes ī‚´But Strings that are permutations of another (such as "eat" and "tea") would all have the same hash code ī‚´Better: ī‚´ From the Java Library! Page 68 final int HASH_MULTIPLIER = 31; int h = 0; for (int i = 0; i < s.length(); i++) { h = HASH_MULTIPLIER * h + s.charAt(i); }
  • 69. Sample Strings and HashCodes ī‚´ The String class implements a good example of a hashCode method ī‚´ It is possible for two or more distinct objects to have the same hash code: This is called a collision ī‚´A hashCode function should minimizes collisions Page 69
  • 70. Computing Object Hash Codes ī‚´ You should have a good hashCode method for your own objects to store them efficiently ī‚´ Override hashCode methods in your own classes by combining the hash codes for the instance variables ī‚´ Then combine the hash codes using a prime-number hash multiplier: Page 70 public int hashCode() { int h1 = name.hashCode(); int h2 = new Double(area).hashCode(); . . . final int HASH_MULTIPLIER = 29; int h = HASH_MULTIPLIER * h1 + h2; return h; }
  • 71. hashCode and equals methods ī‚´hashCode methods should be compatible with equals methods ī‚´If two objects are equal, their hashCodes should match ī‚´a hashCode method should use all instance variables ī‚´The hashCode method of the Object class uses the memory location of the object, not the contents Page 71
  • 72. hashCode and equals methods ī‚´Do not mix Object class hashCode or equals methods with your own: ī‚´Use an existing class such as String. Its hashCode and equals methods have already been implemented to work correctly. ī‚´Implement both hashCode and equals. ī‚´ Derive the hash code from the instance variables that the equals method compares, so that equal objects have the same hash code ī‚´Implement neither hashCode nor equals. Then only identical objects are considered to be equal Page 72
  • 73. 15.5 Stacks, Queues and Priority Queues ī‚´Queues and Stacks are specialized lists ī‚´Only allow adding and removing from the ends Page 73 Insert At Remove At Operation Stack Start(top) Start(top) List in, first out (LIFO) Queue End (tail) Start (head) First in, first out (FIFO) Priority Queue By Priority Highest Priority (Lowest #) Prioritized list of tasks
  • 74. Stacks, Queues and Priority Queues ī‚´Stacks are used for undo features (most recent first) ī‚´Queues are like lines at the bank or store ī‚´Priority Queues remove lowest number first Page 74
  • 76. Stack Example ī‚´The Java library provides a Stack class that implements the abstract stack type’s push and pop operations. ī‚´The Stack is not technically part of the Collections framework, but uses generic type parameters Page 76 Stack<String> s = new Stack<String>(); s.push("A"); s.push("B"); s.push("C"); // The following loop prints C, B, and A while (s.size() > 0) { System.out.println(s.pop()); } The stack class provides a size method
  • 77. Queues and Priority Queues Page 77
  • 78. Priority Queues ī‚´A priority Queue collects elements, each of which has a priority ī‚´Example: a collection of work requests, some of which may be more urgent than others ī‚´It is NOT a FIFO Queue ī‚´Lowest value priority (1) will be removed first Page 78 PriorityQueue<WorkOrder> q = new PriorityQueue<WorkOrder>(); q.add(new WorkOrder(3, "Shampoo carpets")); q.add(new WorkOrder(1, "Fix broken sink")); q.add(new WorkOrder(2, "Order cleaning supplies")); WorkOrder next = q.remove(); // removes “Fix broken sink”
  • 79. 15.6 Stack and Queue Applications ī‚´ Balancing Parenthesis ī‚´Section 2.5, showed how to balance parenthesis by adding 1 for each left ( and subtracting for each right ) ī‚´A stack can be used to keep track of ‘depth’: When you see an opening parenthesis, push it on the stack. When you see a closing parenthesis, pop the stack. If the opening and closing parentheses don’t match The parentheses are unbalanced. Exit. If at the end the stack is empty The parentheses are balanced. Else The parentheses are not balanced. Page 79
  • 80. Using a Stack (Example) ī‚´ Here is a walkthrough of the sample expression ī‚´ We will use the mathematical version (three types of parenthesis) Page 80
  • 81. Reverse Polish Expressions ī‚´ The first handheld calculator used a notation that was easily implemented with a stack: Reverse Polish ī‚´ No parenthesis required if youâ€Ļ ī‚´Input both operands first, then the operator: Page 81 Algebra Reverse Polish (3 + 4) x 5 3 4 + 5 x (3 + 4) x (5 + 6) 3 4 + 5 6 + x
  • 82. Reverse Polish Expressions If you read a number Push it on the stack. Else if you read an operand Pop two values off the stack. Combine the values with the operand. Push the result back onto the stack. Else if there is no more input Pop and display the result. Page 82
  • 83. Reverse Polish Calculator ī‚´ Walkthrough with 3 4 5 + x Page 83
  • 86. Evaluating Algebraic Expressions ī‚´Can be done with two stacks: 1) Numbers 2) Operators ī‚´First Example: 3 + 4 Page 86
  • 87. Expression Example 2 ī‚´Second Example: 3 x 4 + 5 ī‚´Must use precedence (multiply before adding) Page 87
  • 88. Precedence and Expressions (1) ī‚´Third Example: 3 + 4 x 5 ī‚´Keep operators on the stack until they are ready to be evaluated Page 88
  • 89. Precedence and Expressions (2) ī‚´Third Example: 3 + 4 x 5 ī‚´Evaluate top 2 numbers with top operator ī‚´Store result on top of stack ī‚´Evaluate until operator stack is empty Page 89
  • 90. Expressions with Parenthesis (1) ī‚´Fourth Example: 3 x ( 4 + 5 ) ī‚´If (, don’t evaluate. If ), evaluate Page 90
  • 91. Expressions with Parenthesis (2) ī‚´Fourth Example: 3 x ( 4 + 5 ) ī‚´Don’t put ) on stack – evaluate now ī‚´Ignore ( Page 91
  • 92. Precedence Algorithm If you read a number Push it on the number stack. Else if you read a ( Push it on the operator stack. Else if you read an operator op While the top of the stack has a higher precedence than op Evaluate the top. Push op on the operator stack. Else if you read a ) While the top of the stack is not a ( Evaluate the top. Pop the ). Else if there is no more input While the operator stack is not empty Evaluate the top. Page 92 Evaluate the Top: Pop two numbers off the number stack. Pop an operator off the operator stack. Combine the numbers with that operator. Push the result on the number stack.
  • 93. Backtracking (1) ī‚´Uses a stack to solve a maze ī‚´Stack current location, arrow for each possible path 1. We pop off the topmost one, traveling north from (3, 4). Following this path leads to position (1, 4). 2. We now push two choices on the stack, going west or east. Page 93
  • 94. Backtracking (2) 3. Pop off (1, 4) east. It is a dead end. 4. Pop off (1, 4) west. It is a dead end. 5. Now we pop off the path from (3, 4) going east. That too is a dead end. This leaves us with (3, 4) south and (3, 4) west to try Page 94
  • 95. Backtracking (3) 6. Next is the path from (3, 4) going south. At (5, 4), it comes to an intersection. Both choices are pushed on the stack. 7. (5, 4) south is a dead end. 8. (5, 4) west is a dead end. 9. Finally, the path from (3, 4) going west leads to an exit Page 95
  • 96. Maze Solving Pseudocode Push all paths from the point on which you are standing on a stack. While the stack is not empty Pop a path from the stack. Follow the path until you reach an exit, intersection, or dead end. If you found an exit Congratulations! Else if you found an intersection Push all paths meeting at the intersection, except the current one, onto the stack. Page 96
  • 97. Summary: Collections ī‚´A collection groups together elements and allows them to be retrieved later ī‚´A list is a collection that remembers the order of its elements ī‚´A set is an unordered collection of unique elements ī‚´A map keeps associations between key and value objects Page 97
  • 98. Summary: Linked Lists ī‚´A linked list consists of a number of nodes, each of which has a reference to the next node ī‚´Adding and removing elements in the middle of a linked list is efficient ī‚´Visiting the elements of a linked list in sequential order is efficient, but random access is not ī‚´You use a list iterator to access elements of a linked list Page 98
  • 99. Summary: Choosing a Set ī‚´ The HashSet and TreeSet classes both implement the Set interface. ī‚´ Set implementations arrange the elements so that they can locate them quickly. ī‚´ You can form hash sets holding objects of type String, Integer, Double, Point, Rectangle, or Color. ī‚´ You can form tree sets for any class that implements the Comparable interface, such as String or Integer. ī‚´ Sets don’t have duplicates. Adding a duplicate of an element that is already present is silently ignored. ī‚´ A set iterator visits the elements in the order in which the set implementation keeps them. ī‚´ You cannot add an element to a set at an iterator position. Page 99
  • 100. Summary: Maps ī‚´ Maps associate keys with values ī‚´ The HashMap and TreeMap classes both implement the Map interface ī‚´ To find all keys and values in a Map, iterate through the key set and find the values that correspond to the keys ī‚´ A hash function computes an integer value from an object. ī‚´ A good hash function minimizes collisions—identical hash codes for different objects. ī‚´ Override hashCode methods in your own classes by combining the hash codes for the instance variables. ī‚´ A class’s hashCode method must be compatible with its equals method. Page 100
  • 101. Summary: Stacks and Queues ī‚´A stack is a collection of elements with “last-in, first-out” retrieval. ī‚´A queue is a collection of elements with “first-in, first-out” retrieval. ī‚´When removing an element from a priority queue, the element with the most urgent priority is retrieved. Page 101
  • 102. Summary: Problem Solving ī‚´A stack can be used to check whether parentheses in an expression are balanced. ī‚´Use a stack to evaluate expressions in reverse Polish notation. ī‚´Using two stacks, you can evaluate expressions in standard algebraic notation. ī‚´Use a stack to remember choices you haven’t yet made so that you can backtrack to them. Page 102