Documente Academic
Documente Profesional
Documente Cultură
• Bags
• Sets
• Lists
• Stacks
• Queues
1
Making an ADT
Import java.util.Iterator;
public boolean contains(T item); // Does the box contain this item?
public boolean isEmpty(); // Is this box empty?
public int size(); // How many items in the box?
2
Using our BoxADT
…
BoxADT <String> toyBox;
toyBox = new BoxImp<String>();
toyBox.add(“Car”);
toyBox.add(“Plane”);
toyBox.add(“Fred”);
System.out.println(toyBox.contains(“Barbie”));
…
3
Bag ADT
• Bag is a collection with
• no structure or order maintained
• no access constraints (access any item any
time)
• duplicates allowed
• Minimal Operations:
• add(value)
• remove(value) → returns true iff value
removed
• contains(value) → returns true iff value is in
bag
• findElement(value) → returns matching item iff
in bag 4
Bag Applications
• Operations:
• add(value) → true iff value was added (ie, not
duplicate)
• remove(value) → returns true iff value removed (was in
set)
• contains(value) → returns true iff value is in the set
• findElement(value) → returns matching item iff in value in
the set
•…
6
• When do we use a Set instead of a Bag? What
List ADT
if (e.getActionCommand().equals("Add") ){
myJobs.add(askJob());
}
}
else if (e.getActionCommand().equals("Remove") ){
myJobs.remove(askJob());
}
else if (e.getActionCommand().equals("RemoveFrom") ){
10
myJobs.remove(askIndex("from"));
Rest of the example:
public void displayJobs(){
textArea.setText("Jobs to be done\n");
int num = 0;
}
};
• Operations:
• push(value): → Put value on top of stack
• pop() → Removes and returns top of stack
• peek(): → Returns top of stack, without removing
• …
13
Stacks Example
• Reversing the items from a file:
• Read and push onto a stack
• Pop them off the stack
while(! myNums.empty())
textArea.append(myNums.pop() + “\n”);
14
Applications of Stacks
• Programs that deal with programs
• Eg, program execution: call stack/activation stack,
• Eg, expression execution,
• (6 + 4) * ((8 * (6 – 2)) – (7 * 3))
• Undo in editors.
• Assignments:
• #2: reading and checking XML files
• #3: an Undo stack for MiniDraw
15
Evaluating Expressions
16
Queue ADT
• Queues are like Stacks
• Sequence of values
• Constrained access, but:
• Add at the back
• Remove from the front
• Operations:
• offer(value): → Adds value to end of queue
• poll() → Removes and returns front of queue
• peek(): → Returns front of queue, without
removing
•…
• Enqueue, Dequeue
17
Queue Applications
• Used for
• Operating Systems, Network Applications:
• Handling requests/events/jobs that must be done in
order
• Simulation programs
• Managing the events that must happen in the future
• Representing queues in the real world
(traffic, customers, deliveries, ….)
• Search Algorithms
• Computer Games
• Artificial Intelligence
• Priority Queue
18
Javaism
19