220 likes | 345 Views
Computer Science 61B Data Structures and Advanced Programming Lecture 9 – Arrays and Invariants. 2003-09-15 Dan Garcia (www.cs.berkeley.edu/~ddgarcia) Kathy Yelick (www.cs.berkeley.edu/~yelick) inst.eecs.berkeley.edu/~cs61b/ www.ucwise.org 1 Handout: notes. Hurricane Isabel.
E N D
Computer Science 61BData Structures and Advanced ProgrammingLecture 9 – Arrays and Invariants 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
Hurricane Isabel Where is Dan? No office hours this week for Dan
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
Object Integer Account Vector array 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 obj ?
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
objArr 0 intArr 0 1 2 acctArr 0 1 0 0 0 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 new intArr = new int[3]; acctArr = new Account[2]; objArr = new Object[1];
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
0 1 x myBalance 1 2 100 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 Objects Object [] objArr = {new Account(100), new Integer(1)}; objArr[0] = new Integer(2); objArr
x y 0 0 1 1 3 2 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;
tmpArr 0 1 2 intArr myArr 0 0 1 1 2 2 x 3 6 5 3 3 6 6 5 5 “Growing” and “Shrinking” Arrays • Once an array is created, its size does not change • However, we can copy smaller ones to larger ones int [] myArr = {3, 6, 5}; // . . . use myArr, but what if it’s now too small • 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
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.
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
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?
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
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
myDenom myDenom myNumer myNumer 2 8 1 4 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? 12
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
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
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? • public class Landlord { • public Vector myPlots; • Landlord (Vector initP) { myPlots = initP; } • Vector getPlots () { return myPlots; } • Plot plotAt(int i) { return myPlots.get(i); } • } 1: none 2: 2 3: 2&3 4: 2&4 5: 3&4 6: 2-4 7: 2-5
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
Announcements - Quiz • Open book/open notes • Topics: • Basic Java • Writing and using classes and methods • Conditionals, loops, and recursion • Parameter passing • Primitive values vs. objects (and references to them) • public and private • static and non-static • Exceptions • Vectors/Enumerations Note: repOK and loop invariants will not be on this exam • Specifications (@param, @return, @requires, modifies”) • Testing
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