CS61B L06 Control Structures (1) Garcia / Yelick Fall 2003 © UCB
2003-09-15 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
Lecture 9 – Arrays and Invariants
CS61B L06 Control Structures (2) Garcia / Yelick Fall 2003 © UCB
Where is Dan?
Hurricane IsabelNo office hours this week for Dan
CS61B L06 Control Structures (3) Garcia / Yelick Fall 2003 © UCB
Vectors Review• Vectors are objects that look like:
• The boxes can only hold references to objects– Not 1, 2.3, or other basic types.– Can mix objects: 1 Vector may contain Accounts,
Motes, Vectors…• Elements are numbered from 0 to size-1 • Vectors are a mutable type
– The objects can be replaced by other objects– Vectors can grow and shrink
• In Java library: import java.util.*;
0 1 2 3 4
CS61B L06 Control Structures (4) Garcia / Yelick Fall 2003 © UCB
Object: The Universal Parent• Java is an object-oriented language
– One type inherits from another
– You can use the subtype (child type) anywhere the supertype (parent type) is expected
– Given a Vector v of >=2 elements:»Object obj = v.get(1); is legal»obj.intValue() is a compile-time error»(Integer obj).intValue() compiles, but is a
runtime error if obj is not really an Integer »obj.toString() is always legal
… more about this in a couple of weeks
Object
Account Vector arrayInteger
obj
?
CS61B L06 Control Structures (5) Garcia / Yelick Fall 2003 © UCB
Arrays are Similar• Arrays are objects that look like:
• The boxes can hold references to – Objects or primitives, e.g., 1, 2.3– But type of all primitive elements must be the
same• The boxes are numbered from 0 to size-1 • Arrays are a mutable type
– The elements can be replaced by other elements– But, they cannot grow and shrink
• Arrays are built into the Java language, not in the library, so no need to “import”
0 1 2 3 4
CS61B L06 Control Structures (6) Garcia / Yelick Fall 2003 © UCB
Creating Arrays• Declaration uses [] and element type:
int [] intArr; can contain int values
Account [] acctArr; can contain “Account” refs, or nulls
Object [] objArr; can contain any Object ref, or nulls
• To create array object, use newintArr = new int[3];
acctArr = new Account[2];
objArr = new Object[1];
intArr acctArr 0 1
objArr 0
20 1
0 0 0
CS61B L06 Control Structures (7) Garcia / Yelick Fall 2003 © UCB
Using Arrays• One can get/set elements using [] syntax:
intArr[0] = 0; // don’t rely on defaults for now
intArr[1] = 2;
intArr[2] = 4;
int y = intArr[1];
• As with Vectors, need to have the object before using it:int [] a2;
a2[0] = 2; // error – no array allocated yet
• Shorthand for initialization (only with decl):int [] a3 = {2, 4, 6};
a2 = {1, 2, 3}; // not allowed
CS61B L06 Control Structures (8) Garcia / Yelick Fall 2003 © UCB
Types and Arrays• Arrays element types must match
declaration:intArr[1] = new Account(100); // compiler error
intArr[1] = new Integer(1); // compiler error
• But you can have an array of ObjectsObject [] objArr = {new Account(100),
new Integer(1)};
objArr[0] = new Integer(2);objArr 0 1
myBalance
1001
2
x
CS61B L06 Control Structures (9) Garcia / Yelick Fall 2003 © UCB
Multidimensional Arrays• A multidimensional array in Java is an array
of arrays:int [][] x = new int [3][2];
int [][] y = new int[2][];
y[0] = new int[2];
y[1] = new int[1]
y[1][0] = 3;
x
12
0
y
1
0
3
CS61B L06 Control Structures (10) Garcia / Yelick Fall 2003 © UCB
“Growing” and “Shrinking” Arrays
• Once an array is created, its size does not change
• However, we can copy smaller ones to larger onesint [] myArr = {3, 6, 5};
// . . . use myArr, but what if it’s now too small
intArr 20 1
3 6 53 6 5
tmpArr 20 1
x
myArr 20 1
3 6 5
int [] tmpArr = new int [2*myArr.length + 1];
for (int k = 0; k < myArr.length; k++) {
tmpArr[k] = myArr[k];
} // rest of tmpArr uninitialized (default 0)
myArr = tmpArr;
• See also System.arrayCopy
CS61B L06 Control Structures (11) Garcia / Yelick Fall 2003 © UCB
An Aside: Understanding main• Recall the signature of the main method:
public static void main (String [] args)
• This says main takes an array of Strings• E.g.,
public static void main (String [] args) {
System.out.println(args[0]);
int i = Integer.parseInt(args[1]);
System.out.println(“args[1] = “ + i);
}
• As with reading from System.in, more error checking should be used.
CS61B L06 Control Structures (12) Garcia / Yelick Fall 2003 © UCB
Administrivia• Reading assignments
– For Wednesday : Liskov 10 and – For Friday: ADW Chapter 8
• CSUA Help session for advanced Unix postponed.
• HW #3 due tomorrow @ 11:59pm – Correction in hw3.html (api was OK).
» See hw3/Errata.txt (similarly for proj1)
• Quiz in 1 week1: Monday, 2003-09-22– In-class, open book/notes, last2 slides contains topics
• Project #1 handed out on Friday, due ~2 wks
CS61B L06 Control Structures (13) Garcia / Yelick Fall 2003 © UCB
Designing Data Abstractions• Major questions to answer:
– How does the abstract object behave to the outside world? (the specification)
– How do we represent the data internally in our implementation? (the implementation)
– What properties do we enforce on the state of our internal representation? (representation invariant)
– How does a concrete value map to an abstract one? (abstraction function)
• Project 1: design a Landlord class– Specification: given
» Do not add public methods that your tester tests– Implementation: Use a Vector of plots
» Options: store “rented” or “vacant”, sorted?
CS61B L06 Control Structures (14) Garcia / Yelick Fall 2003 © UCB
Representation Invariant• Representation invariant: a property of
the concrete (implementation) object that holds on entry/exit of all methods in the class– What values may private instance variables have?– Methods assume the invariant holds on entry – Methods that change the instance variables must
ensure the invariant still holds when they exit
• Why use a representation invariant? – Allows us to reason about the correctness of each
method in isolation– May make some method faster or easier to write– Self-discipline: you make up and enforce the rules
CS61B L06 Control Structures (15) Garcia / Yelick Fall 2003 © UCB
Representation Invariant - Fraction
• Recall: Fractions are immutable (in the abstract), and toString() shows in reduced form
• Possible invariants for the Fraction class:– weak invariant: myDenom != 0
» toString() can’t assume anything, always must reduce
– weak invariant with benevolent side-effects» Same as above, except toString() replaces instance
variables with reduced form after calling gcd()» “Benevolent” because it does a good thing
•Future calls to gcd will be very fast•The side effect is not user-visible
– strong invariant: always store in reduced form» myDenom != 0 AND gcd(myNumer, myDenom) == 1
CS61B L06 Control Structures (16) Garcia / Yelick Fall 2003 © UCB
Abstraction Function• Expresses the “meaning” of the values in the object’s
instance variables as a whole– Tells us how interpret the concrete state of the instance variables
to recover the abstract object they represent
• This Fraction object represents the abstract rational number ½ :
• So does this one:
• Abstraction functions are often many-to-one– Several concrete states may represent the same abstract object
• The abstraction function for Fraction is division:– AF(c) = c.myNumer / c.myDenom
Do 3 different implementation have different AFs?
1 myNumer
2 myDenom
4 myNumer
8 myDenom
1
2
CS61B L06 Control Structures (17) Garcia / Yelick Fall 2003 © UCB
Representation Invariant – repOk()
• Often a good idea to include a “self-test” method that checks whether the invariant holds:
/* @return true if the object representation * is in a legal state satisfying the invariant, * otherwise return false */
public boolean repOk() { return ((myDenominator != 0) &&
(gcd(myNumer, myDenom) == 1)); }
• When to call repOk?– When invariant may be broken: at the end of all constructors
and methods that change the object (mutators) as a self-diagnostic
– Also on entry to methods that rely on the invariant
• Since check may be costly, may turn it off in “released” version of code using:
assert repOk(); // more in next lecture
CS61B L06 Control Structures (18) Garcia / Yelick Fall 2003 © UCB
Representation Exposure• A well-designed data abstraction can
guarantee its representation invariants– Variables are usually private to ensure invariants
• User may still be able to violate the invariants– Representation exposure: giving the user of an
abstract data type access to the internals, allowing them to violate representation invariants
• If all fields are private, how does this happen?– Taking mutable objects from user and putting
them into the internal state– Returning mutable parts of the state
CS61B L06 Control Structures (19) Garcia / Yelick Fall 2003 © UCB
PRS Question• The following code for proj1 has as an invariant: Plots in myPlot (which store the beginning/size) do not overlap
• How many “lines” need to be changed to ensure the user cannot break the invariant?
1: none 2: 2 3: 2&34: 2&45: 3&46: 2-47: 2-5
1) public class Landlord {2) public Vector myPlots; 3) Landlord (Vector initP) {
myPlots = initP; }4) Vector getPlots () {
return myPlots; }5) Plot plotAt(int i) {
return myPlots.get(i); }6) }
CS61B L06 Control Structures (20) Garcia / Yelick Fall 2003 © UCB
Data Abstraction Summary• Data Abstraction is a powerful programming tool
– Provide an abstract data object and a set of useful operations to the outside world
– Hide the implementation details
• Representation Invariant– Rules about how the internal variables are managed– Include a repOk() method that checks whether any of the
rules have been violated at run time
• Abstraction Function– Describes the mapping from your concrete representation
using instance variables to the abstract object your class represents
• Benevolent side effects– Modifications of internal state that are not externally visible
CS61B L06 Control Structures (21) Garcia / Yelick Fall 2003 © UCB
Announcements - Quiz• Open book/open notes• Topics:
– Basic Java
1. Writing and using classes and methods
2. Conditionals, loops, and recursion
3. Parameter passing
4. Primitive values vs. objects (and references to them)
5. public and private
6. static and non-static
7. Exceptions
8. Vectors/Enumerations
Note: repOK and loop invariants will not be on this exam– Specifications (@param, @return, @requires, modifies”)– Testing
CS61B L06 Control Structures (22) Garcia / Yelick Fall 2003 © UCB
Announcements - Quiz• Review session
– Tuesday or Wednesday evening: watch newsgroup for details
• Exam questions often use examples you have seen. – We will include the code, but you will have time problems if
you’re seeing it for the first time.
• Examples from labs and homeworks (through lab 4 and homework 3):– Account– Fraction– StringFormat (hw)– StringCheck (lab)– IslamicDate– Vector and Enumeration (lab)
• Solutions for labs and homeworks online
Top Related