230 likes | 349 Views
Computer Science 61B Data Structures and Advanced Programming Arrays & Implementing Enumerations Lecture 12. 2003-09-24 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. Arrays - Review.
E N D
Computer Science 61BData Structures and Advanced ProgrammingArrays & Implementing EnumerationsLecture 12 2003-09-24 Dan Garcia(www.cs.berkeley.edu/~ddgarcia) Kathy Yelick (www.cs.berkeley.edu/~yelick) inst.eecs.berkeley.edu/~cs61b/www.ucwise.org1 Handout:notes
Arrays - Review • Declaration uses [ ] and element type: int [] intArr; • To create array object, use new intArr = new int[3]; • One can get/set elements using [ ] syntax: intArr[2] = 4; int y = intArr[1]; • Need to have the object before using it: int [] a2; a2[0] = 2;// error a2 is not initialized • Shorthand for initialization (only with decl): int [] a3 = {2, 4, 6}; a3[3]; // array bounds error at runtime
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.
Using Arrays • Arrays are very common inside other abstract data types (ADTs) • Those ADTs want to hide • Details of growing and shrinking • How much of array is actually full • Iteration over “filled” elements on the array • Simple design problem: Sequence of Strings • Similar to Vectors but much simpler • Gives you a flavor of what Vector implementation might look like • You’ll be using this in Lab 5
0 1 2 s one two two Sequence of Strings • Key methods: • Constructor: Creates an empty Sequence • insertElementAt: inserts a String at a position • Shifts elements to the right by 1 to make room • Fills in nulls for any extra spaces • toString and size: usual • Abstract view: Sequence s = new Sequence (); s.insertElementAt(“two”, 1) s.insertElementAt(“one”, 1)
myStrings mySize 3 Sequence of Strings Example • Start with hiding first two features: • (1) Grow/shrink sequence as needed • (2) Which elements are “filled in” • Represent a sequence with two variables: • mySize is the “logical” size of the Sequence • myStrings is an array with at least enough storage • Make larger arrays as needed (in Lab) • Possible concrete view: 0 1 2 3 4
Properties of Sequence • Representation Invariant: • mySize is the “logical” size of the Sequence • At least enough storage for that many public class Sequence {… /* Invariant: myString.length >= mySize; */ private String [] myStrings; // space for elts private int mySize; // # of elts used } • Abstraction Function: • toString defines the Abstraction Function (typical) • Note that null before mySizedo appear in the abstract view of the object • nulls after do not
Implementing Enumerations • The current ADT spec (all the methods for Sequence) is a very weak class • can only get elements out by doing toString • Need more observers • Sequences are similar to Vectors • Would like to be able to Enumerate over them • How do we build our own Enumeration? • Two separate problems: • How to make a class that behaves like an Enumeration • How to implement the class so that it can keep track of the position (and the Sequence being enumerated)
Interfaces • Enumeration is a Java Interface • From "Application Programming Interface (API)" • Specifies a set of class, that implement the interface • What method they have (and common semantics) • All enumerations have: • nextElement() • hasMoreElements() • We write a generic loop or method that works for any kind of enumeration: public void print(Enumeration e) { while (e.hasMoreElements()) { System.out.println(e.nextElement + “ “); } }
Implementing Interfaces • To make a class SequenceEnumeration act like others Enumerations • Need to “implement” the Enumeration interface • Use the implements keyword in the class header class SequenceEnumeration implements Enumeration { // definition of hasMoreElements and nextElement // declaration of variables for the Enumeration } • Next problem: what information to keep and how to implement SequenceEnumeration
0 1 2 3 4 mySequence myStrings myPosition mySize 2 4 SequenceEnumeration • What will we need inside an Enumeration, e.g., for nextElement and hasMoreElements? • An int to keep track of the current position • Some way of keeping track of which Sequence • Can do this by building a class with two fields public class SequenceEnumeration { // … lots omitted private Sequence mySequence; private int myPosition; } Inelegant: Why?
Accessing Internal State • nextElement needs to access the elements of myStrings: • But myStrings is private • Making it public completely opens the abstraction (someone could set the array to null!) • Fix: define the SequenceEnumeration class inside the Sequence class. public class Sequence { . . . // invariant myString.length >= mySize; String [] myStrings; // space for elements int mySize; // number of elements private class SequenceEnumeration { … int myPosition } }
Inner Classes • An inner class is a class defined within another class (similar to Scheme nested defines) • The inner class may only be visible to the enclosing class (we will make it private) • The inner class can see private things in the enclosing class • In SequenceEnumeration it can see the • myStrings array and mySize int • Only additional information needed to implement the Enumeration is • myPosition, which is an int
Getting the Enumeration Out • So now we have: public class Sequence { ... String [] myStrings; int mySize; private class SequenceEnumeration implements Enumeration { // define hasMoreElements, nextElement ... int myPosition; } } • How do we get a SequenceEnumeration?
The elements() method • Trick: Use a public interface, but a private implementation • Add a new (observer) method to Sequence public Enumeration elements () { return new SequenceEnumeration(); } • The constructor for SequenceEnumeration: public SequenceEnumeration () { myPosition = 0; }
Using Enumerations • Example using an Enumeration on a Sequence public String toString ( ) { String s = "["; Enumeration enum = elements ( ); if (!enum.hasMoreElements ( )) { return s + "]"; } s = s + (String) enum.nextElement ( ); while (enum.hasMoreElements ( )) { s += "," + (String) enum.nextElement (); } return s + "]"; }
A Few More Details • The SequenceEnumeration implementation is private • can only access it through the public interface, Enumeration • Because the return type of nextElement is Object, a cast is required: • String s = (String) enum.nextElement(); • The nextElement method should throw an exception if we’ve run out of elements: • NoSuchElementException
Peer Instruction • When implementing an interface, you can only have the public methods that implement the interface, not any extra public ones • A class may only implement 1 interface at a time • Interfaces are a very important part of the Java language and are used often by the SW industry. ABC 1: FFF 2: FFT 3: FTF 4: FTT 5: TFF 6: TFT 7: TTF 8: TTT What is the veracity of these statements?
Administrivia • Reading assignments • For today : Interfaces ADW 12.9 • For Friday: Linked Lists • NEW LAB POLICY • If we get the Lab online by Monday's lecture, you have to finish & check-off your lab during lab. • If it's not online in time, the policy defaults to the current one (due in first 1/2-hr of next lab) • We'll announce in Monday's lecture whether it's up • Register your PRS devices in lab • http://test-2.media.berkeley.edu/Transmitter/index.cfm
Quiz Commentary • Many people got Q1a,f (and other Q1s) wrong • This indicates they didn't understand very basic call-by-value and copy-vs-same {I=1; J=I; I=2; println(J);} issues • Many of these were covered explicitly in the review session • This might cause lots of lost sleep with big projects, fix now • Q2 Specs question caused the most grumbling • Specs are important. They define the API "line" • On the whole, we were pleased with the quiz and the overall student results. Ans, grading standard soon • It was probably a leeeeetle on the wordy side, agreed • If you're struggling, come to TA/our office hours • If you want a regrade (after checking grading std) • Write request on paper, staple to front of exam & give to TA. We regrade entire exam; score could drop as a result!
Project 1 Update…life on a pier • Due in less than a week (before October) • If you haven't started the project…START NOW!!! • Please read newsgroup before posting; use our thread • An Errata will be posted soon to clarify many Qs • Rishi has written a GUI to help you with your testing • Autograder WAS run @ 5am • It will probably change -- version number
Project Peer Instruction • How far into the project are you? 1: 10% 2: 20% 3: 30% … … 8: 80% 9: 90% 0: FIN