cs61b l12 arrays and implementing enumerations (1)garcia / yelick fall 2003 © ucb 2003-09-24 dan...
TRANSCRIPT
CS61B L12 Arrays and Implementing Enumerations (1) Garcia / Yelick Fall 2003 © UCB
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
Computer Science 61BData Structures and Advanced Programming
Arrays & Implementing Enumerations Lecture 12
CS61B L12 Arrays and Implementing Enumerations (2) Garcia / Yelick Fall 2003 © UCB
Arrays - Review• Declaration uses [ ] and element type:
int [] intArr;
• To create array object, use newintArr = 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
CS61B L12 Arrays and Implementing Enumerations (3) 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 L12 Arrays and Implementing Enumerations (4) Garcia / Yelick Fall 2003 © UCB
Using Arrays• Arrays are very common inside other
abstract data types (ADTs)• Those ADTs want to hide
1.Details of growing and shrinking2.How much of array is actually full3.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
CS61B L12 Arrays and Implementing Enumerations (5) Garcia / Yelick Fall 2003 © UCB
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)
s 0 1
two twoone
2
CS61B L12 Arrays and Implementing Enumerations (6) Garcia / Yelick Fall 2003 © UCB
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 myStrings
mySize
3
CS61B L12 Arrays and Implementing Enumerations (7) Garcia / Yelick Fall 2003 © UCB
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 mySize do appear in the abstract view
of the object– nulls after do not
CS61B L12 Arrays and Implementing Enumerations (8) Garcia / Yelick Fall 2003 © UCB
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)
CS61B L12 Arrays and Implementing Enumerations (9) Garcia / Yelick Fall 2003 © UCB
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 + “ “); }}
CS61B L12 Arrays and Implementing Enumerations (10) Garcia / Yelick Fall 2003 © UCB
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
CS61B L12 Arrays and Implementing Enumerations (11) Garcia / Yelick Fall 2003 © UCB
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 fieldspublic class SequenceEnumeration { // … lots omitted
private Sequence mySequence;
private int myPosition;
}
mySequence
myPosition
2
0 1 2 3 4 myStrings
mySize
4
Inelegant: Why?
CS61B L12 Arrays and Implementing Enumerations (12) Garcia / Yelick Fall 2003 © UCB
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 } }
CS61B L12 Arrays and Implementing Enumerations (13) Garcia / Yelick Fall 2003 © UCB
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
CS61B L12 Arrays and Implementing Enumerations (14) Garcia / Yelick Fall 2003 © UCB
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?
CS61B L12 Arrays and Implementing Enumerations (15) Garcia / Yelick Fall 2003 © UCB
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; }
CS61B L12 Arrays and Implementing Enumerations (16) Garcia / Yelick Fall 2003 © UCB
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 + "]";}
CS61B L12 Arrays and Implementing Enumerations (17) Garcia / Yelick Fall 2003 © UCB
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
CS61B L12 Arrays and Implementing Enumerations (18) Garcia / Yelick Fall 2003 © UCB
Peer Instruction
A. When implementing an interface, you can only have the public methods that implement the interface, not any extra public ones
B. A class may only implement 1 interface at a time
C. Interfaces are a very important part of the Java language and are used often by the SW industry.
ABC1: FFF2: FFT 3: FTF4: FTT5: TFF6: TFT7: TTF8: TTT
What is the veracity of these statements?
CS61B L12 Arrays and Implementing Enumerations (19) Garcia / Yelick Fall 2003 © UCB
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
CS61B L12 Arrays and Implementing Enumerations (21) Garcia / Yelick Fall 2003 © UCB
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!
CS61B L12 Arrays and Implementing Enumerations (22) Garcia / Yelick Fall 2003 © UCB
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