95-712 java collections1 java 2 collection classes
Post on 20-Dec-2015
241 views
TRANSCRIPT
95-712 Java Collections 1
Java 2 Collection Classes
95-712 Java Collections 2
The core collection interfaces
A Collection is a group of objects. A Map is a set of associations between objects.
95-712 Java Collections 3
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 4
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 5
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 6
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 7
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() methodCollection of values via values() methodSet of key-value mappings via entrySet()
• Methods include put(key,value) and get(key)
95-712 Java Collections 8
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 9
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 10
Abstract Classes
AbstractCollection Partial implementation of the Collection interfaceMakes 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 byextending the appropriate abstract class.
In what follows we will be using existing (built-in) classes.
95-712 Java Collections 11
Concrete Classes
95-712 Java Collections 12
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 13
// 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 14
// 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 15
// 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 16
// Output
Larry in set
The set contains 4 elements
The set contains 3 elements
Curly Joe
Larry
Moe
95-712 Java Collections 17
// 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 18
public int getValue() { return value; }
public String toString() { return "[" +
uniqueIdentifier + "] = " + value;
}
public int hashCode() {
return uniqueIdentifier.hashCode();
}
95-712 Java Collections 19
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 20
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 21
[Y] = 45
[X] = 23
//Output
95-712 Java Collections 22
// 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 23
java FindDups It depends what the meaning of is is .
Duplicate detected: is
8 distinct words detected: [what, depends, the, It, ., is, meaning, of]
//Output
95-712 Java Collections 24
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 25
// 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 26
// 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 setSystem.out.println("The set contains " + set.size() + " elements");
95-712 Java Collections 27
// 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 28
/*Larry in setThe set contains 4 elementsThe set contains 3 elementsCurly JoeLarryMoe*/
95-712 Java Collections 29
// 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 30
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 31
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 32
/*[X] = 23[Y] = 45*/
95-712 Java Collections 33
// Demonstration of TreeSet FindDups2.java// Note how the output is ordered
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 34
System.out.println(s.size() + " distinct words detected: " + s);
}}
/*java FindDups2 It depends what the meaning of is is .Duplicate detected: is8 distinct words detected: [., It, depends, is, meaning, of, the, what]*/
95-712 Java Collections 35
Class LinkedList ExtendsAbstractsSequentialList Implements List
•get, remove, insert at the beginning and end of the list
•Allow linked lists to be used as a stack, queue, or double- ended queue (deque)
•Doubly linked list is used
95-712 Java Collections 36
// 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 37
// 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 38
java UseQueueBAC
95-712 Java Collections 39
// 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 40
// 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 41
/*CAB*/
95-712 Java Collections 42
Class ArrayList Extends AbstractListImplements 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 43
Class HashMap Extends AbstractMapImplements 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 functionis good
O(n + tablesize) for iteration
95-712 Java Collections 44
// 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 45
System.out.println(m.size() + " distinct words detected:");System.out.println(m);
}}
/*
java Freq that's a hard way to go go6 distinct words detected:{a=1, hard=1, go=2, to=1, way=1, that's=1}
*/
95-712 Java Collections 46
// 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 47
// 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 elementtable.put("123456789", "Curly Joe");
// see if it's therename = (String)table.get("123456789");
if(name != null) System.out.println(name);
95-712 Java Collections 48
// remove an elementtable.remove("165987651");
// display the whole table by calling its toString() methodSystem.out.println(table);
}
}
/*java UseHashMapMoeNot in tableCurly Joe{123456789=Curly Joe, 123456543=Moe}*/
95-712 Java Collections 49
// 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 50
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 51
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 52
Output
Y=[Y45]X=[X23]
But we are using Strings as keys.
95-712 Java Collections 53
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()); } }}
We could also use the IntVariable as a key…
95-712 Java Collections 54
Output
[Y45]=Tue Jun 17 11:40:25 EDT 2008[X23]=Tue Jun 17 11:40:25 EDT 2008
95-712 Java Collections 55
Class TreeMap Extends AbstractMapImplements SortedMap
Red-Black tree based implementation of SortedMapinterface
Log(n) for contains key, get, put, remove
95-712 Java Collections 56
// 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 57
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 go6 distinct words detected:{a=1, hard=1, go=2, to=1, way=1, that's=1}
*/
95-712 Java Collections 58
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 59
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 60
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 61
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 62
Red Black TreeConstraints
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 63
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 64
Suppose we add a leafand the parent is black.We color the leaf red (heavyline). If the other child is blackor empty then we are done.
95-712 Java Collections 65
New Node
Black Parent
recolor
Red Parent (unless it’sthe root then it stays black.
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 nodehaving three keys. We need to fix it. We transform the red-black tree by coloring both children black andthe parent red. If the parent is the root it stays black.
95-712 Java Collections 66
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 67
A
B
C
Single rotate left. Recolor as above. Continue up the tree.
A
B
C
A
B
C
New node
95-712 Java Collections 68
A
C
B New node
B
A
C
B
A C
B
A C
Rotate Right Rotate Left Recolor
See if any more work needs done.
Double Rotation
New node
95-712 Java Collections 69
Insert 100, 10, 80, 50, 20, 6, 95, 72, 55
Red Black Tree Insertions
100 100 100 80 80 80 80 80 // // // \\ / \ / \ / \ // \ 10 10 10 100 10 100 10 100 10 100 20 100 \\ \\ \\ / \ 80 50 50 10 50 // 20
Can you finish?