DOC PREVIEW
Berkeley COMPSCI 61B - Lecture Notes

This preview shows page 1 out of 4 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 4 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 4 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CS61B Lecture #5: Arrays and ObjectsArraysA Few SamplesExample: Accumulate ValuesExample: Insert into an ArrayGrowing an ArrayObject-Based ProgrammingPhilosophyYou Saw It All in CS61A: The Account classThe PiecesGetter MethodsClass Variables and MethodsInstance Methods `Instance' and `Static' Don't MixConstructorsSummary: Java vs. CS61A OOP in SchemeCS61B Lecture #5: Arrays and Objects• For faster response, please send urgent problems (like “the lab filesdon’t compile”) as mail to cs61b, rather than using class messages.• Homeworks are generally due by the next lab.• For next week, please readHead First Java,chapters 5 and 6.Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 1Arrays• An array is structured container whose components are– length, a fixed integer.– a sequence of length simple containers of the same type, num-bered from 0.– (.length field usually implicit in diagrams.)• Arrays are anonymous, like other structured containers.• Always referred to with pointers.• For array pointed to by A,– Length is A.length– Numbered component i is A[i] (i is theindex)– Important feature: index can beany integer expression.Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 2A Few SamplesJava Resultsint[] x, y, z;String[] a;x = new in t[3];y = x;a = new St ring[3];x[1] = 2;y[1] = 3;a[1] = "H ello";int[] q;q = new in t[] { 1, 2, 3 };// Short form for dec larations:int[] r = { 7, 8, 9 };x: 0 3 0y:z:a:Helloq: 1 2 3r: 7 8 9Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 3Example: Accumulate ValuesProblem: Sum up the elements of array A.static i nt s um (in t[] A) {int N;N = 0; // New (1 .5) syntaxfor (int i = 0; i < A.length; i += 1) for (int x : A)N += A[i]; N + = x;return N ;}// For th e ha rd-core: could have writte nint N, i;for (i=0, N=0; i<A.length; N += A[i], i += 1){ } // or jus t ;// But pl ease don’ t: it’ s obscure.Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 4Example: Insert into an ArrayProblem: Want a call like insert ( A, 2, "gnu ") to convert (destruc-tively)A: beargazellehartebeestskunkA: beargazellegnuhartebeestto/** Insert X at location K in AR R , moving items* K, K+1, ... to locations K+1, K+2, ... .* The last item in ARR is l ost. */static void insert (String[] arr, int k, Str ing x) {for (int i = ar r . length-1; i > k ; i -= 1) // Why ba c k wards?arr[i] = arr[i-1];// Alternative to t his loop:// System.arraycopy ( arr, k,| {z }fromarr, k+1,| {z }toarr.length-k-1| {z }# to copy);arr[k] = x;}Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 5Growing an ArrayProblem: Suppose that we want to change the description above, sothat A = insert2 (A, 2, "gnu") doesnotshove “skunk” off the end,but instead “grows” the array.A: beargazellehartebeestskunkA: beargazellegnuhartebeestskunkto/** Return array, r, where r . l e n gth = A R R.length+1; r[0..K-1]* the same as ARR[0..K-1], r[k] = x, r[K + 1 ..] same as ARR[K..]. */static String[] insert2 (String[] arr, i nt k, String x) {String[] result = n ew String[arr.length + 1];System.arraycopy (arr, 0, result, 0, k);System.arraycopy (arr, k, result, k+1, a rr.length-k);result[k] = x;return result;}• Why do we need a different return type from insert??Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 6Object-Based ProgrammingBasic Idea.•Function-based programsare organized primarily around the func-tions (methods, etc.) that do th i ngs. Data structures (objects ) areconsidered separate.•Object-based programsare organized around thetypes of objectsthat are used to represent data; meth ods are grouped by type ofobject.• Simple banking-system example:accountdepositaccountaccountwithdrawaccountFunction-basedAccountdepositwithdraw balance: 1420ExportedmethodsExportedfieldObject-basedLast modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 7Philosophy• Idea (from 1970s and before): Anabstract data typeis– a set of possible values (adomain), plus– a set ofoperationson those values (or their containers).• In IntList, for example, the domain was aset of pairs:(head,tail),where head is an int and tail is a pointer to an IntList.• The In tList operations consisted only of a ssigning to and accessingthe two fields (head and tail).• In general, prefer a purelyprocedural interface,where the func-tions (methods) do everything—no outside access to fields.• That way, implementor of a class and its methods ha s complete con-trol over behavior of instances.• In Java, the preferred wa y to write the “operations of a type” is asinstance methods.Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 8You Saw It All in CS61A: The Account class(define-class (account balance0)(instance-vars (balance 0))(initialize(set! balance balance0))(method (deposit amount)(set! balance (+ balance amount))balance)(method (withdraw amount)(if (< balance amount)(error "Insufficient funds")(begin(set! balance (- balance a m o u n t))balance))) )(define my-account(instantiate account 1000))(ask my-account ’balance)(ask my-account ’deposit 100)(ask my-account ’withdraw 500)public class Account {public int balance;public Account (int balance0) {balance = balance0;}public int deposit (int am o u n t ) {balance += amount; return balance;}public int withdraw (int a m o u n t) {if (balance < amount)throw new IllegalStateException("Insufficient funds");else balance -= amount;return balance;}}Account myAccount = new Account (1 0 0 0);myAccount.balancemyAccount.deposit (100);myAccount.withdraw(500);Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 9The Pieces• Class declaration defines anew type of object,i.e., new type ofstructured container.• Instance variables such as balance a re the s i mple containers withinthese objects (fieldsorcomponents).• Instance methods, such as deposit and withdraw are like ordinary(static) methods that take an invisible extra parameter (called th i s).• The new operator creates (instantiates) new objects, and initializesthem using constructors.• Constructors such as the method-like declaration of Account a respecial methods that are used only to initialize new instances. Theytake their arguments from the new expression.• Method selection picks methods to call. For example,myAccount.deposit(100)tells us to call the method named deposit that is defined for th eobject pointed to by myAccount.Last modified: Fri Jan 27 14:45:24 2006 CS61B: Lecture #5 10Getter Methods• Slight problem with Java


View Full Document

Berkeley COMPSCI 61B - Lecture Notes

Documents in this Course
Lab

Lab

4 pages

Matrix

Matrix

3 pages

Numbers

Numbers

14 pages

Lectures

Lectures

12 pages

Project 1

Project 1

24 pages

Exam

Exam

8 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?