Download 07_Collections

Document related concepts
no text concepts found
Transcript
Java 2 Collection Classes
95-712 Java Collections
1
A Collection is a group of objects.
A Map is a set of
associations between
objects.
The core collection interfaces
95-712 Java Collections
2
The Collection Interface
•Root of a hierarchy
•Some collections allow duplicates others do not
•This interface allows you to pass collections around
•Has generic methods such as contains() ,isEmpty(),
iterator() and size()
95-712 Java Collections
3
The Set Interface Extends Collection
•At most one null element
•No duplicates, i.e., no elements such that e1.equals (e2)
•If you try to add a duplicate then the add method
returns false
95-712 Java Collections
4
The SortedSet Interface Extends Set
•Guarantees that its iterator will traverse the
set in ascending element order, sorted
according to the natural ordering of its
elements or by a comparator provided at
sorted set creation.
•If no comparator is specified then all elements
of the set must implement the Comparable
interface.
•CompareTo or Compare is used.
95-712 Java Collections
5
The List Interface Extends Collection
•An ordered collection or sequence
•Access by integer position
•Access by search
•Duplicates allowed
•Like arrays--zero based
•In some implementations, positional operations may
execute in time proportional to the index value
•Can return an Iterator (hasNext(), next(), remove()) or
ListIterator(hasNext(), hasPrevious(), add(),…)
•Add and remove can be done at end or at a particular
index
95-712 Java Collections
6
The Map Interface (Key, Value pairs)
• Root of a hierarchy
•No duplicate keys, duplicate values are okay
•Three collection views
Set of keys via keySet() method
Collection of values via values() method
Set of key-value mappings via entrySet()
• Methods include put(key,value) and get(key)
95-712 Java Collections
7
The SortedMap Interface Extends Map
A map that guarantees that it will be in ascending
key order
Sorted by natural ordering of its keys or by a
comparator provided at SortedMap creation
time
Ordering must be consistent with equals. It uses
the compare or compareTo methods
95-712 Java Collections
8
Abstract Classes
General Notes:
• Can’t be instantiated
• A subclass of an abstract class can be instantiated if it
overrides each abstract method in the superclass and
provides a body for each.
95-712 Java Collections
9
Abstract Classes
AbstractCollection
Partial implementation of the Collection interface
Makes it easy to define custom Collection implementations
AbstractSet, AbstractList and so on…
Partial implementation of these interfaces
If you want to create your own custom built Collections, start by
extending the appropriate abstract class.
In what follows we will be using existing (built-in) classes.
95-712 Java Collections
10
Concrete Classes
95-712 Java Collections
11
Class HashSet Extends AbstractSet
•Implements set interface
•Backed by a hash table (HashMap instance)
•No guarantees as to iteration order
•O(1) for add, remove, contains, size -- if the hash
function is good
•Iteration depends on O(N + tablesize)
95-712 Java Collections
12
// Demonstration of HashSet
UseHashSet.java
import java.util.*;
public class UseHashSet {
public static void main(String args[]) {
// create a set object -- this is a HashSet implementation
Set set = new HashSet();
95-712 Java Collections
13
// Add some values to the set
set.add("Moe");
set.add("Curly");
set.add("Larry");
set.add("Larry");
set.add("Curly Joe");
// does the set contain "Larry"
if(set.contains("Larry")) System.out.println("Larry in set");
// how many elements are in the set
System.out.println("The set contains " + set.size() + " elements");
95-712 Java Collections
14
// remove "Curly"
set.remove("Curly");
System.out.println("The set contains " + set.size() + " elements");
// iterate over the contents of the set and display the values
// first, create an iterator object based on this set
Iterator myIter = set.iterator();
// use two of the three iterator methods -- hasNext(), next(), remove()
while(myIter.hasNext()) {
String name = (String) myIter.next();
System.out.println(name);
}
}
}
95-712 Java Collections
15
// Output
Larry in set
The set contains 4 elements
The set contains 3 elements
Curly Joe
Larry
Moe
95-712 Java Collections
16
// Storing objects other than Strings
// UseHashSet2.java
// override Object's hashCode() and equals()
import java.util.*;
class IntVariable {
private String uniqueIdentifier;
private int value;
public IntVariable(String name, int value) {
uniqueIdentifier = name;
this.value = value;
}
95-712 Java Collections
17
public int getValue() { return value; }
public String toString() { return "[" +
uniqueIdentifier + "] = " + value;
}
public int hashCode() {
return uniqueIdentifier.hashCode();
}
95-712 Java Collections
18
public boolean equals(Object other) {
if(other != null && getClass() == other.getClass()) {
IntVariable otherVar = (IntVariable) other;
return(uniqueIdentifier.equals(otherVar.uniqueIdentifier));
}
else return false;
}
}
95-712 Java Collections
19
public class UseHashSet2 {
public static void main(String args[]) {
Set symbolTable = new HashSet();
IntVariable x = new IntVariable("X",23),
y = new IntVariable("Y",45);
symbolTable.add(x);
symbolTable.add(y);
Iterator iter = symbolTable.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
}
}
95-712 Java Collections
20
//Output
[Y] = 45
[X] = 23
95-712 Java Collections
21
// Demonstrate HashSets
FindDups.java
// Note how the output is not ordered
import java.util.*;
public class FindDups{
public static void main(String args[]) {
Set s = new HashSet();
for(int i = 0; i < args.length; i++) {
if(!s.add(args[i]))
System.out.println("Duplicate detected: " + args[i]);
}
System.out.println(s.size() + " distinct words detected: "
+ s);
}
}
95-712 Java Collections
22
//Output
java FindDups It depends what the meaning of is is .
Duplicate detected: is
8 distinct words detected: [what, depends, the, It, ., is, meaning, of]
95-712 Java Collections
23
Class TreeSet Extends AbstractSet
•Implements set
•Backed by Treemap
•Ascending element order (natural order or
comparator)
•O(Log(n)) for the methods add, remove, and contains
95-712 Java Collections
24
// Demonstrate a TreeSet
UseTreeSet.java
import java.util.*;
public class UseTreeSet {
public static void main(String args[]) {
// create a set object -// This is a Red Black tree implementation
Set set = new TreeSet();
95-712 Java Collections
25
// Add some values to the set
set.add("Moe");
set.add("Curly");
set.add("Larry");
set.add("Larry");
set.add("Curly Joe");
// does the set contain "Larry"
if(set.contains("Larry")) System.out.println("Larry in set");
// how many elements are in the set
System.out.println("The set contains " + set.size() + " elements");
95-712 Java Collections
26
// remove "Curly"
set.remove("Curly");
System.out.println("The set contains " + set.size() + " elements");
// iterate over the contents of the set and display the values
// first, create an iterator object based on this set
Iterator myIter = set.iterator();
// use two of the three iterator methods -- hasNext(), next(), remove()
while(myIter.hasNext()) {
String name = (String) myIter.next();
System.out.println(name);
}
}
}
95-712 Java Collections
27
/*
Larry in set
The set contains 4 elements
The set contains 3 elements
Curly Joe
Larry
Moe
*/
95-712 Java Collections
28
// Adding objects to a set
UseTreeSet2.java
// storing objects other than Strings
// implement Comparable
import java.util.*;
class IntVariable implements Comparable {
private String uniqueIdentifier;
private int value;
public IntVariable(String name, int value) {
uniqueIdentifier = name;
this.value = value;
}
95-712 Java Collections
29
public int getValue() { return value; }
public String toString() { return "[" + uniqueIdentifier + "] = " + value; }
public int compareTo(Object other) {
if(other != null && getClass() == other.getClass()) {
IntVariable otherVar = (IntVariable) other;
return(uniqueIdentifier.compareTo(otherVar.uniqueIdentifier));
}
else throw new ClassCastException("Illegal IntVariable Compare");
}
}
95-712 Java Collections
30
public class UseTreeSet2 {
public static void main(String args[]) {
Set symbolTable = new TreeSet();
IntVariable x = new IntVariable("X",23),
y = new IntVariable("Y",45);
symbolTable.add(x);
symbolTable.add(y);
Iterator iter = symbolTable.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
}
}
95-712 Java Collections
31
/*
[X] = 23
[Y] = 45
*/
95-712 Java Collections
32
// Demonstration of TreeSet
// Note how the output is ordered
FindDups2.java
import java.util.*;
public class FindDups2{
public static void main(String args[]) {
Set s = new TreeSet();
for(int i = 0; i < args.length; i++) {
if(!s.add(args[i]))
System.out.println("Duplicate detected: " + args[i]);
}
95-712 Java Collections
33
System.out.println(s.size() + " distinct words detected: " + s);
}
}
/*
java FindDups2 It depends what the meaning of is is .
Duplicate detected: is
8 distinct words detected: [., It, depends, is, meaning, of, the, what]
*/
95-712 Java Collections
34
Class LinkedList Extends
AbstractsSequentialList Implements List
•get, remove, insert at the beginning and end of the list
•Allow linked lists to be used as a stack, queue, or doubleended queue (deque)
•Doubly linked list is used
95-712 Java Collections
35
// Queue Demonstration
UseQueue.java
import java.util.*;
public class UseQueue {
public static void main(String args[]) {
// create a linked list
LinkedList queue = new LinkedList();
95-712 Java Collections
36
// add a few characters to the end of the queue
queue.addLast(new Character('B'));
queue.addLast(new Character('A'));
queue.addLast(new Character('C'));
// remove all the elements from the front and display
while(!queue.isEmpty()) {
Character c = (Character) queue.removeFirst();
char c2 = c.charValue();
System.out.println(c2);
}
}
}
95-712 Java Collections
37
java UseQueue
B
A
C
95-712 Java Collections
38
// Demonstrate Stacks in Java
UseStack.java
import java.util.*;
public class UseStack {
public static void main(String args[]) {
// create a linked list
LinkedList stack = new LinkedList();
95-712 Java Collections
39
// push a few characters on the top of the stack
stack.addFirst(new Character('B'));
stack.addFirst(new Character('A'));
stack.addFirst(new Character('C'));
// pop all the elements and display them
while(!stack.isEmpty()) {
Character c = (Character) stack.removeFirst();
char c2 = c.charValue();
System.out.println(c2);
}
}
}
95-712 Java Collections
40
/*
C
A
B
*/
95-712 Java Collections
41
Class ArrayList Extends AbstractList
Implements List
•Implemented by a resizable array
•O(1) for size, isempty, get, set, iterator, listiterator
•Add runs in amortized constant time, adding n
elements requires O(n) time
•Capacity grows automatically
•Details of add and growth are not specified
95-712 Java Collections
42
Class HashMap Extends AbstractMap
Implements Map
Hash table based implementation of map
No guarantees as to the order of the map
O(1) for operations like get and put if hash function
is good
O(n + tablesize) for iteration
95-712 Java Collections
43
// Demonstration of HashMap
Freq.java
import java.util.*;
public class Freq {
private static final Integer ONE = new Integer(1);
public static void main(String args[]) {
Map m = new HashMap();
for(int i = 0; i < args.length; i++) {
Integer freq = (Integer) m.get(args[i]);
m.put(args[i], (freq == null ?
ONE :
new Integer(freq.intValue() + 1)));
}
95-712 Java Collections
44
System.out.println(m.size() + " distinct words detected:");
System.out.println(m);
}
}
/*
java Freq that's a hard way to go go
6 distinct words detected:
{a=1, hard=1, go=2, to=1, way=1, that's=1}
*/
95-712 Java Collections
45
// HashMap demonstration
UseHashMap.java
import java.util.*;
public class UseHashMap {
public static void main(String args[]) {
// create a hash table
Map table = new HashMap();
// add a few id's and names to the table
table.put("123456543", "Moe");
table.put("123456789", "Curly");
table.put("165987651", "Larry");
95-712 Java Collections
46
// query the table
String name = (String)table.get("123456543");
if(name != null) System.out.println(name);
name = (String)table.get("111223333");
if(name != null) System.out.println(name);
else System.out.println("Not in table");
// replace an element
table.put("123456789", "Curly Joe");
// see if it's there
name = (String)table.get("123456789");
if(name != null) System.out.println(name);
95-712 Java Collections
47
// remove an element
table.remove("165987651");
// display the whole table by calling its toString() method
System.out.println(table);
}
}
/*
java UseHashMap
Moe
Not in table
Curly Joe
{123456789=Curly Joe, 123456543=Moe}
*/
95-712 Java Collections
48
// HashMap demonstration
SymbolTable.java
// storing objects other than Strings
import java.util.*;
class IntVariable {
private String uniqueIdentifier;
private int value;
public IntVariable(String name, int value) {
uniqueIdentifier = name;
this.value = value;
}
95-712 Java Collections
49
public int hashCode() { return uniqueIdentifier.hashCode(); }
public boolean equals(Object other) {
if(other != null && getClass() == other.getClass()) {
IntVariable otherVar = (IntVariable) other;
return(uniqueIdentifier.equals(otherVar.uniqueIdentifier));
}
else return false;
}
public int getValue() { return value; }
public String getID() { return uniqueIdentifier; }
public String toString() { return "["+uniqueIdentifier+value+"]"; }
}
95-712 Java Collections
50
public class SymbolTable {
public static void main(String args[]) {
Map symbolTable = new HashMap();
IntVariable x = new IntVariable("X",23),
y = new IntVariable("Y",45);
symbolTable.put(x.getID(), x);
symbolTable.put(y.getID(), y);
Set s = symbolTable.entrySet();
Iterator iter = s.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
}
}
95-712 Java Collections
51
Output
Y=[Y45]
X=[X23]
But we are using Strings as keys.
95-712 Java Collections
52
We could also use the IntVariable as a key…
public class SymbolTable {
public static void main(String args[]) {
Map symbolTable = new HashMap();
IntVariable x = new IntVariable("X",23),
y = new IntVariable("Y",45);
symbolTable.put(x, new Date());
symbolTable.put(y, new Date());
Set s = symbolTable.entrySet();
Iterator iter = s.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
}
}
95-712 Java Collections
53
Output
[Y45]=Tue Jun 17 11:40:25 EDT 2008
[X23]=Tue Jun 17 11:40:25 EDT 2008
95-712 Java Collections
54
Class TreeMap Extends AbstractMap
Implements SortedMap
Red-Black tree based implementation of SortedMap
interface
Log(n) for contains key, get, put, remove
95-712 Java Collections
55
// TreeMap demonstration
Freq2.java
import java.util.*;
public class Freq2 {
private static final Integer ONE = new Integer(1);
public static void main(String args[]) {
Map m = new TreeMap();
95-712 Java Collections
56
for(int i = 0; i < args.length; i++) {
Integer freq = (Integer) m.get(args[i]);
m.put(args[i], (freq == null ?
ONE :
new Integer(freq.intValue() + 1)));
}
System.out.println(m.size() + " distinct words detected:");
System.out.println(m);
}
}
/*
java Freq2 that's a hard way to go go
6 distinct words detected:
{a=1, hard=1, go=2, to=1, way=1, that's=1}
*/
95-712 Java Collections
57
Notes on Red-Black Trees
• Used in Java
• Is a special Binary Search Tree (less than
goes left, greater than goes right).
• Always balanced
• O(Log N) for delete,insert,lookup
• A nice way to implement a 2-3 tree
• We will focus on insert and lookup
• Deletion is tricky
95-712 Java Collections
58
Red Black Trees
• A balanced Binary Search Tree
• Very clever and fun
• Start by understanding 2-3 trees
– no more than 2 keys per node
– no more than three children per node
– temporary overflow is ok
– insert at the leaf
– the tree has a flat bottom
95-712 Java Collections
59
2-3 Tree Insertions
Insert 100, 10, 80, 50, 20, 6, 95, 72, 55
100
10,100 10,80,100 => 80
/ \
10 100
80
80
20, 80
/ \
/
\ => / | \
10,50 100 10,20,50 100
10 50 100
Can you finish?
95-712 Java Collections
60
Red Black Tree
• Nodes and edges are either red or black
• The root is always black
• The color of any edge connecting a
parent to a child is the same as the
color of the child node
95-712 Java Collections
61
Red Black Tree
Constraints
1. On any path from a root to a leaf, the number
of black edges is the same.
2. A red node that is not a leaf has two black
children
3. A black node that is not a leaf has either
• two black children; or
• one red child and one black child; or
• a single child which is a red leaf
95-712 Java Collections
62
Red Black Tree Insertions
• Find a leaf where insertion should occur
• Color new leaf red
• If parent is black two cases:
– if the other child is black or empty then we
have formed a 2-3 tree three node and we
are done.
– If the other child is red then we have
violated constrain 3. We must recolor the
edges.
95-712 Java Collections
63
Suppose we add a leaf
and the parent is black.
We color the leaf red (heavy
line). If the other child is black
or empty then we are done.
95-712 Java Collections
64
Black Parent
New Node
Red Parent (unless it’s
the root then it stays black.
recolor
Black child
Black child
But here we add a leaf (and paint it red) and the other child is also red. In a 2-3 tree, this corresponds to a node
having three keys. We need to fix it. We transform the red-black tree by coloring both children black and
the parent red. If the parent is the root it stays black.
95-712 Java Collections
65
Red Black Tree Insertion
• On the other hand, if the parent is red
then it cannot be the root and we must
perform a single or double rotation and
then we must recolor the two red edges
black and the parent red (if it’s not the
root).
95-712 Java Collections
66
Single
rotate left.
Recolor as
above.
Continue
up the tree.
A
B
B
A
B
C
A
C
C
New node
95-712 Java Collections
67
Rotate Right
Rotate Left
A
A
C
B
Recolor
New node
B
A
B
C
C
New node
B
A
See if any more work needs done.
C
Double Rotation
95-712 Java Collections
68
Red Black Tree Insertions
Insert 100, 10, 80, 50, 20, 6, 95, 72, 55
100
100 100
//
//
10
10
\\
80
80
// \\
10 100
80
/ \
10 100
80
/ \
10 100
\\
50
80
/ \
10 100
\\
50
//
20
80
// \
20 100
/ \
10 50
Can you finish?
95-712 Java Collections
69