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• Readings for next week:Blue ReaderChapter 6.• Readings on language details:Java Language Specification,Chapter10 (Arrays), Chapter 8 and 9. Again, this material is dense, and Idon’t want you to try to memorize. Do try to get as much out of i tas you easily can, and save up que stions to ask i n lecture, discussion,or by e-mail. Feel free to ignore particularly mystifying sections, orthings we aren’t interested in just now: notably sections on strictfp,volatile, transient, native, synchronized, nested and inner classes,instance and static initializers (8.6–8.7), and e nums (8 . 9).• For faster response, please send urgent problems (like “the lab filesdon’t compile”) as mai l to cs61b, rather than using class messages.Last modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 1Arrays• An array is structured conta i ner whose components are– length, a fixed integer.– a sequence of length simple containers of the same type, num-bered from 0.– (.le ngth field us ua l l y implicit in diagrams.)• Arrays are anonymous, like other s tructured containers.• Always referred to with pointers.• For array pointed to by A,– Length is A.length– Numbered comp onent i i s A[i] (i is theindex)– Important feature: index can beany integer expression.Last modified: Mon Sep 20 03:03:54 2004 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 declarations:int[] r = { 7, 8, 9 };x: 0 3 0y:z:a:Helloq: 1 2 3r: 7 8 9Last modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 3Example: Accumulate ValuesProblem: Sum up the elements of array A.static i nt sum (int[] A) {int N;N = 0; // New (1 .5) sy ntaxfor (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 writtenint 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 obs cure.Last modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 4Example: Insert into an ArrayProblem: Want a cal l like ins ert (A, 2, "gnu") to convert (destruc-tively)A: beargazellehartebeestskunkA: beargazellegnuhartebeestto/** Insert X at location K in AR R , moving ite ms* K, K+ 1, ... to locatio n s K+1, K+2, ....* The l ast item in ARR is lost. */static void insert (String[] arr, int k, String x) {for (int i = arr.length-1; i > k; i -= 1) // Why backw a rds?arr[i] = arr[i-1];// Alternative to this loop:// System.arraycopy ( arr, k,| {z }fromarr, k+1,| {z }toarr.length-k-1| {z }# to copy);arr[k] = x;}Last modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 5Growing an ArrayProblem: Suppose that we want to change the descri ption above, sothat A = insert2 (A, 2, "gnu") doesnotshove “skunk” off the end,but instead “grow s” the a rray.A: beargazellehartebeestskunkA: beargazellegnuhartebeestskunkto/** Return array, r, where r.length = ARR.length+1; r[0..K-1]* the s ame as ARR[0..K-1], r[k] = x, r[K+1..] same as ARR[K..]. */static String[] insert2 (String[] arr, int k, String x) {String[] result = new String[arr.length + 1];System.arraycopy (arr, 0, result, 0, k);System.arraycopy (arr, k, result, k+1, arr.l ength-k);result[k] = x;return result;}• Why do we need a different return type fr om insert??Last modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 6Object-Based ProgrammingBasic Idea.•Function-based programsare org a nized primari l y around the func-tions (methods, etc.) that do things. Data structures (objects) areconsidered separate.•Object-based programsare organized around thetypes of objectsthat are used to represent data; methods are grouped by type ofobject.• Simple banking-system e xample:accountdepositaccountaccountwithdrawaccountFunction-basedAccountdepositwithdraw balance: 1420ExportedmethodsExportedfieldObject-basedLast modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 7Philosophy• Idea (from 1970s and before): A nabstract data typeis– a set of possible values (adomain), plus– a set ofoperationson those value s (or their containers).• In IntList, for example, the domain was aset of pair s:(head,tail),where head is an int and tail is a pointer to an IntList.• The IntList operations consisted only of ass i g ning to and accessingthe two fields (head and tail).• In gener al, prefer a purelyprocedural inte rface,where the func-tions (methods) do everything—no outside access to fields.• That way, implementor of a class and its methods has complete con-trol over behavior of instances.• In Java, the preferred way to write the “operations of a type” is asinstance methods.Last modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 8You Saw It All in CS61A: The Account class(define-class (a c c ount balance0)(instance-vars (balanc e 0))(initialize(set! balance balance 0 ) )(method (deposit amount)(set! balance (+ balance amount))balance)(method (withdra w amount)(if ( < balance amount)(error "Insufficient funds")(begin(set! balance (- balance amount))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 balance 0 ) {balance = balance0;}public int deposit (int amount) {balance += amount; return balanc e ;}public int withdraw (int amount) {if (b alance < amount)throw new IllegalStateException("Insufficient f u n ds");else balance -= amount;return balance;}}Account myAccount = new Account (1000);myAccount.balancemyAccount.deposit (100 );myAccount.withdraw(500);Last modified: Mon Sep 20 03:03:54 2004 CS61B: Lecture #5 9The Pieces• Class declaration defines anew type of object,i.e., new type ofstructured container.• Instance variables such as balanc e are the simple containers withinthese obje cts (fieldsorcomponents).• Instance methods, such as de posit and withdra w are like ordinar y(static) methods that take an invisible extra parame ter (called this).• The new operator creates (instantiates) new objects, and
View Full Document