cs61b l08 vectors, enumeration & project 1 (1)garcia / yelick fall 2003 © ucb never forget…
TRANSCRIPT
CS61B L08 Vectors, Enumeration & Project 1 (1) Garcia / Yelick Fall 2003 © UCB
Never forget…
CS61B L08 Vectors, Enumeration & Project 1 (2) Garcia / Yelick Fall 2003 © UCB
2003-09-12 Dan Garcia
(www.cs.berkeley.edu/~ddgarcia)
Kathy Yelick (www.cs.berkeley.edu/~yelick)
inst.eecs.berkeley.edu/~cs61b/www.ucwise.org1 Handout: notes
Computer Science 61BData Structures and Advanced Programming
Vectors, Enumerations & Project 1 Lecture 8
CS61B L08 Vectors, Enumeration & Project 1 (3) Garcia / Yelick Fall 2003 © UCB
Using Collections of Data• So far, we have only seen simple
datatypes– Primitives– Classes with 1 or more primitives or references to
other objects• In Scheme, most interesting data
structures involved linked lists & trees (built on lists)
• In Matlab, most interesting data structures involved an array
• We can easily use both of these in Java.– Start with vectors– These are an ordered collection of objects…
CS61B L08 Vectors, Enumeration & Project 1 (4) Garcia / Yelick Fall 2003 © UCB
Primitive types vs. Objects• For primitive types (int, boolean, …), there is a
corresponding Object type– E.g., int is the primitive type, Integer is the Object type
• Conversion goes both ways, e.g., int<->Integer
– E.g.,To make a new Integer object from an int, you simply say new Integer(3);
– E.g.,To get an int from an Integer object num, you can use num.intValue();
• Why is this important?– Certain methods require the Object, others the primitive
types– The Object type is more powerful, however "heavier weight"– true or false evaluation is always done w/the primitive
type
CS61B L08 Vectors, Enumeration & Project 1 (5) Garcia / Yelick Fall 2003 © UCB
Vectors• Vectors are objects that look like:
• The boxes can only hold references to objects– Not 1, 2.3, or other primitive types.
• The boxes are numbered from 0 to size-1 so you can ask for or set the ith element
• Vectors are a mutable type– They can grow and shrink– The objects can be replaced by other objects
• Need to “import” using: import java.util.Vector;
0 1 2 3 4
CS61B L08 Vectors, Enumeration & Project 1 (6) Garcia / Yelick Fall 2003 © UCB
Using VectorsVector v = new Vector ( );
v.addElement(new Integer(4));
2
4
v.addElement(new Integer(1));
0
1
v.addElement(new Integer(2));
1
2
v
6
X
v.setElementAt(new Integer(6), 2);
v.size( ) -> 3
v.elementAt(2) -> Integer 4
CS61B L08 Vectors, Enumeration & Project 1 (7) Garcia / Yelick Fall 2003 © UCB
The Contents of Vectors• Vectors can contain references to any Object
– I.e., things built by “new <ClassName>”– Not primitive types
• For example, elementAt has the signature public Object elementAt(int index)
• Given v defined on previous slides = v.elementAt(2);
= v.elementAt(2);
• What types of variables can appear on the left-hand side of the assignments?
Object o
Integer elem
(Integer)
CS61B L08 Vectors, Enumeration & Project 1 (8) Garcia / Yelick Fall 2003 © UCB
More Examples using Vectors• Which of the following are legal?
System.out.println(“Element at index 2: “ + v.elementAt(2));
v.elementAt(1).equals(v.elementAt(2))v.elementAt(1).intValue()((Integer) v.elementAt(1)).intValue()
• intValue() is defined on Integer, so you need to tell the compiler the element is an Integer
OK
OK (false)Compiler errorOK
CS61B L08 Vectors, Enumeration & Project 1 (9) Garcia / Yelick Fall 2003 © UCB
Casts and Vectors• Casts are used to tell the compiler what kind
of Object something is.– v.addElement(new Account(100));– Account kathy = (Account) v.elementAt(3);– Integer elem = (Integer) v.elementAt(2);
• You can lie to the compiler about some things:– kathy = (Account) v.elementAt(1);
• But these programs won’t run• You can’t lie to the compiler about non-
Objects, nor can you cast to/from them– int i = (int) v.elementAt(1); // Not Allowed
CS61B L08 Vectors, Enumeration & Project 1 (10) Garcia / Yelick Fall 2003 © UCB
Efficiency of Vector Operations
Vector() constructor
elementAt()/get(), setElementAt()/set()
elements()
addElement()
insertElementAt(), removeElementAt(), remove()
size()
constant time - O(1)
constant time - O(1)(averaged over many calls)
All linear time - O(n)
constant time - O(1)
constant time - O(1)
constant time - O(1)
CS61B L08 Vectors, Enumeration & Project 1 (11) Garcia / Yelick Fall 2003 © UCB
Iterating Over Vectors• Often want to do something to look at or
change all elements of a Vector• One way is to use a loop: for (int j = 0; j < v.size(); j++) { if (v.elementAt(j) == null) { v.setElementAt(new Integer(0),j); } }• What if we want to do something with all non-
null elements?• Can we abstract this?• Control abstraction: Similar to “map” in
Scheme
CS61B L08 Vectors, Enumeration & Project 1 (12) Garcia / Yelick Fall 2003 © UCB
Vectors and Enumerations• A Vector is an example of a collection, like
lists or trees• Enumerating or iterating over all of the
elements of collection is common (and can be complicated for things like trees)
• The conventional way of doing this in Java is:// (Assuming v is a Vector) Enumeration enum = v.elements();while (enum.hasMoreElements()) { System.out.println(“Another elem: “ + enum.nextElement());}
• The Vector v is not changed by the above
CS61B L08 Vectors, Enumeration & Project 1 (13) Garcia / Yelick Fall 2003 © UCB
Visualizing Enumerations
• Think of an Enumeration object as containing a “hidden finger” that sits on the current position in a collection
• Every time you call nextElement(), you get the current item and the finger is advanced
• hasMoreElements() asks if the finger has another item for you or has passed the end
0 1 2 3 4 enum
CS61B L08 Vectors, Enumeration & Project 1 (14) Garcia / Yelick Fall 2003 © UCB
Vectors and Enumerations• Lets take this apart:
// (Assuming v is a Vector)
Enumeration enum = v.elements();
while (enum.hasMoreElements()) {
System.out.println(“Another elem: “ +
enum.nextElement());
}
Creates an “Enumeration” object specifically for this Vector
See if the Enumeration has anything left unseen
Return the next (unseen) element
Move the “current position” to the next position
CS61B L08 Vectors, Enumeration & Project 1 (15) Garcia / Yelick Fall 2003 © UCB
Vectors and Enumerations• Another way to do it
// (Assuming v is a Vector)
for (Enumeration e = v.elements() ;
e.hasMoreElements() ; ) { System.out.println(e.nextElement());}
Creates an “Enumeration” object specifically for this Vector
See if the Enumeration has anything left unseen
Return the next (unseen) element
Move the “current position” to the next position
CS61B L08 Vectors, Enumeration & Project 1 (16) Garcia / Yelick Fall 2003 © UCB
Summary: Vectors & Enumerations
• Vectors provide a clean interface for storing collections of objects
• Most Vector methods are relatively efficient, but a few (like insertElementAt() and removeElementAt()) have hidden costs– Because they have to “slide down” elements to
perform an insertion or deletion and preserve the ordering
• Enumerations provide a “handy” way to traverse a collection (the hidden finger)– Methods for getting the nextElement() and asking
if the enumeration hasMoreElements()
CS61B L08 Vectors, Enumeration & Project 1 (17) Garcia / Yelick Fall 2003 © UCB
Peer Instruction: Enumerations
// v has the following elements: [0 1 2 3]Enumeration enum = v.elements();while (enum.hasMoreElements()) { Integer i = (Integer) enum.nextElement(); System.out.print (i); if (i != null && i.intValue() == 1) { v.remove(i); }}
1: 0123 2: 012 3: 0134: 0235: 016: Err7: UndefWhat is the output of this program?
CS61B L08 Vectors, Enumeration & Project 1 (18) Garcia / Yelick Fall 2003 © UCB
Administrivia• Reading assignments
– For Mon : Liskov 5 (repOk), ADW Chapter 8 (testing)
• In-class Quiz in 10 days covering basic Java– Open book, open notes, short answers – Similar to Peer Instruction questions)– Example Midterms on 61B Portal
• Project #1 online tonight by 11:59pm– Due before October (last minute of September
30th)– No homework will be due the week of the project
CS61B L08 Vectors, Enumeration & Project 1 (19) Garcia / Yelick Fall 2003 © UCB
Project 1 Overview
• You're the Landlord of a pier on the Marina• You number your property by spaces [0, landSize-1]• Clients want to lease vacant, contiguous-spaced
plots• They don't care where that plot is located• You need to find a "big-enough chunk" of free space• They will sometimes vacate their plot, leaving holes• You can't ever move an existing tenant• How do you find vacant spaces in your pier?
CS61B L08 Vectors, Enumeration & Project 1 (20) Garcia / Yelick Fall 2003 © UCB
Life as a Landlord…• Three algorithms to find a big-enough chunk
on your property to satisfy a lease request:
1. FIRST FIT: Always find the first chunk you see as you walk out onto the pier.
2. NEXT FIT: Remember where the end of the last space you leased was and look for the next chunk which starts after that space. (If you don’t find one by the time you reach the end you then return [i.e., wrap-around] to the start of the pier to continue searching until you reach your starting space.)
3. BEST FIT: Try to find the chunk which fits best, i.e., whose size most closely matches the request (equal to or bigger). If there’s a tie, choose the one closest to the shore.
CS61B L08 Vectors, Enumeration & Project 1 (21) Garcia / Yelick Fall 2003 © UCB
Big-enough chunks• If you CAN find a a big-enough chunk (of
contiguous vacant spaces) to satisfy the lease request, you…– Place the client closest to shore within the chunk– Given that the pier extends out to the right, we
call this operation "Left-justifying the request" (LJ)– Remember that you have just leased those
spaces– Return a Plot to your new tenant (the Plot object
has a selector called startsAt()indicating where)
• If you CAN'T find one you return null.
CS61B L08 Vectors, Enumeration & Project 1 (22) Garcia / Yelick Fall 2003 © UCB
Example for landSize=7
• Ana LEASE 2• Dan LEASE 1• Ana VACATE• Kathy LEASE 1• Ana LEASE 1• Omar LEASE 3• Kathy VACATE• Ana VACATE• Mike LEASE 1
FIRST_FIT NEXT_FIT BEST_FIT0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6
CS61B L08 Vectors, Enumeration & Project 1 (23) Garcia / Yelick Fall 2003 © UCB
And in conclusion…• Vectors are ways to store Objects in an
easy-to-access way
• Enumerations allow you to extract Objects from a Collection one at a time– Don't mutate the Vector while enumerating over
it!
• Project 1 will be online before tomorrow– START EARLY!! START THIS WEEKEND!!
CS61B L08 Vectors, Enumeration & Project 1 (24) Garcia / Yelick Fall 2003 © UCB
Example for landSize = 7
• Ana LEASE 2• Dan LEASE 1• Ana VACATE• Kathy LEASE 1• Ana LEASE 1• Omar LEASE 3• Kathy VACATE• Ana VACATE• Mike LEASE 1
FIRST_FIT NEXT_FIT BEST_FIT0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6