CS61B Lecture Notes

download CS61B Lecture Notes

of 41

Transcript of CS61B Lecture Notes

  • 8/11/2019 CS61B Lecture Notes

    1/41

    CS61B Lecture 1 (1/22) 1/22/2014 11:30:00 PM

    Logistics

    Jonathan Shewchuk [email protected]

    Prof + all TAs (preferred) [email protected]

    http://www.cs.berkeley.edu/~jrs/61b

    Piazza board is required reading.

    Reading: Sierra & Bates pp. 1-9, 18-19, 84

    First Homework Due Wednesday 1/29

    Buy 61B reader (has old exams) at Vick Copy on Euclid via Hearst

    Grading

    10 Labs

    20 Homeworks

    70 Projects

    25 Midterm I

    25 Midterm II

    50 Final Exam

    No Code Rule

    Never have possession of someone elses code

    1-line exception: Compiler error message -> cut & paste entire error

    message including line of code

    Goals of CS61B

    1. Learning efficient data structures & algorithms

    2. Designing & writing large programs

    3. Understanding & designing data abstraction & interfaces

    4. Learning Java

    Definitions

    Objected-oriented programming

    o Object: a repository of data.

    o Class: type of object.

    o Method: another word for procedure/function that operates

    on an object or class.

    e.g. addItem: adds an item to any ShoppingList object

    mailto:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]://www.cs.berkeley.edu/~jrs/61bhttp://www.cs.berkeley.edu/~jrs/61bhttp://www.cs.berkeley.edu/~jrs/61bmailto:[email protected]:[email protected]
  • 8/11/2019 CS61B Lecture Notes

    2/41

    o Inheritance: A class may inherit properties from a more

    general class

    e.g. ShoppingList inherits from List the property of

    storing a sequence of items

    o

    Polymorphism: One method works on several classes if theclasses need different implementations.

    e.g. addItem method on every kind of List, though

    adding item to a ShoppingList is a different from a

    ShoppingCart

    o Object-oriented: Each object knows its own class and

    methods

    Java

    Variables: you must declare them and their type.

    o Python: x = 1

    o Scheme: (let ((x 1)))

    o Java: int x;

    x = 1;

    Does 2 things:

    Allocates memory to store an integer

    Names variable x

    Variables also used to reference objects.o 2 ways to get classes:

    Use on defined by somebody else. Java has tons.

    Define your own.

    String myString;

    o Can store a reference to a String object

    myString = new String();

    new String() is a constructor

    assignment = causes myString to reference new

    String object

    Java programs must be compiled before you can run them.

    o Java program (.java) javac .class files java (Java

    Virtual Machine (JVM) Answer

    Objects and Constructors

  • 8/11/2019 CS61B Lecture Notes

    3/41

    String s; //step 1: declare a string variable

    s = new String(); //step 2, 3: construct empty string; assign it to s.

    String s = new String(); //step 1, 2, 3 combined.

    s = Yow!;

    String s2 = s //Now s and s2 reference same object (String Yow!)s2 = new String(s); //Now referencing 2 different, identical objects

    Look where s points.

    Follows reference to string object.

    Reads string

    Constructs new string with copy of characters

    Makes s2 reference new string

    3 String Constructors:

    new Strings() constructs an empty strings (zero characters)

    Yow!

    new String(s) takes a parameter s

    Constructors always have same name as their class, except stuffinquotes.

    Methods

    s2 s.toUppercase();

    s2 YOW!

    String s3 = s2.concat(!!); //s3 = s2 + !!;

    s3 YOW!!!String s4 = *.concat(s2).concat(*); //s4 = * + s2 + *;

    s4 *YOW!*

    The object s Yow! did not change.

    Strings are immutable. Their contents never change.

    I/O Classes and Objects

    Objects in System class for interacting with a user:

    System.out is a PrintStream object then that outputs to the screen.

    System.in is an InputStream object that reads from the keyboard.

    readLine is defined on BufferedReader objects.

    How do we construct a BufferedReader?

    With an InputStreamReader.

    InputStreamReader reads raw data

    How do we construct a InputStreamReader?

  • 8/11/2019 CS61B Lecture Notes

    4/41

    With an InputStream.

    InputStream compose into characters (2 bytes long)

    How do we construct a InputStream?

    System.in is one.

    Compose into entire lines of text.How do we figure all this out?

    Figure this out via online Java libraries API java.io

    import java.io.*;

    Class SimpleIO {

    public static void main(String[] arg) throws Exception {

    BufferedReader keybd =

    New BufferedReader(new InputStreamReader(System.in));

    System.out.println(keybd.readLine());

    }

    }

    To use Java libraries other than java.lang, you import them.

    Java.io includes InputStreamReader, BufferedReader, etc.

    Java program always begins at a method called main

  • 8/11/2019 CS61B Lecture Notes

    5/41

    CS61B Lecture 2 (1/27) 9/15/2014 12:31:00 PM

    Announcements

    Unix/Vim Help Session Tomorrow(1/28) 6pm 306 Soda

    Defining Classes

    Fields: Variables stored in objectso aka instance variables

    Fields are addressed like methods but fields dont have parenthesis

    after it.

    o amanda.age field

    o amanda.introduce() method call

    class Human {/** class definition*/

    public int age;

    public String name;

    public void introduce() {/**method definition*/

    System.out.println(Im + name + and Im + age + years

    old.);

    }

    public void copy(Human original) {

    age = original.age

    name = original.name

    }

    public Human(String givenName) {/** this is a constructor*/age = 6;

    name = Amanda

    }

    }

    }

    Human amanda = New Human(Amanda)

    Human amanda = new Human();/** creates Human object*/

    amanda.age = 6;/**assigns 6 to amanda.age*/

    amanda.name = Amanda;/**assigns the string Amanda to

    amanda.name to*/

    amanda.introduce();

    public Human() {/**Default constructor takes no parameters, does no

    initializing*/

    }

  • 8/11/2019 CS61B Lecture Notes

    6/41

    Public Human() {/**Override default constructor */

    age = 0

    name = untitled

    }

    public void change(int age) {String name = Tom;

    this.age = age;

    this.name = name;

    }

    amanda.introduce() implicitly passes an object (amanda) as a parameter

    called this.

    Important:You CANNOT change the value of this!

    this = amanda;/** compile time error if you do this*/

    The static keyword

    static field: a single variable shared by a whole class of objects

    also called a class variable

    System.in & System.out are static fields Staticmethod: Doesnt implicitly pass an object as a parameter.

    public static void printHumans() {

    System.out.println(numberOfHumans);

    }

    Important: In a static method, THERE IS NO this!

  • 8/11/2019 CS61B Lecture Notes

    7/41

    CS61B Lecture Notes (1/29) 1/22/2014 11:30:00 PM

    Primitive Types

    byte: 8-bit integer range: -128 127 (1 bit used for +/-, 7 for #s)

    short: 16-bit integer range: -32768 32767

    int 32 - bit range: -2million 2 million

    long 64-bit: -9 quintillion 9 quintillionlong x = 43L;//stores 43 as long type

    double: A 64-bit floating-point number

    o used for numbers with a decimal point

    float: 32-bit

    boolean: true or false

    char: A character (2 bytes long, 16 bits, never negative, always

    positive of 0)

    char c = h;

    double and float values must have a decimal point

    double y = 18.0

    float f = 43.9f;

    Objects types Primitive types

    Contains a reference value

    How defined? Class definition Built into Java

    How created? new 6, 3.4, true

    How initialized? Constructor Default (usually zero)

    How used? Method Operators (+, *)

    -x x*y

    x+y x/yfor integers, rounds toward

    zero (drops remainder).

    x-y x%yremainder of x/y (integers

    only)

    Java.lang library:

    Math class

    x = Math.abs(y);

    x = Math.sqrt(y);

  • 8/11/2019 CS61B Lecture Notes

    8/41

    Integer class

    int x = Integer.parseInt(1984);

    Double class

    Double d = Double.parseDouble(3.14)

    Integers can be assigned to variables of longer typesint i = 43;

    long l = 43;

    l = i

    i = l //Compiler Error

    i = (int)l;//int cast

    a b a && b a || b !a

    f f f f t

    f t f t

    t f f t f

    t t t t

    Created by comparison operators ==, , =, !=

    boolean x = 3 == 5;//x is false

    x = 4.5 >= 4.5;//true

    x = 4 != 5-1;

    x = false == (3 == 0);//true

    Conditionals

    if (boolValue) {

    statements

    }

    boolean pass = score >= 75;if (pass) {

    output(You pass CS61B);

    } else {

    //score < 75

    output(You are such an unbelievable loser.);

  • 8/11/2019 CS61B Lecture Notes

    9/41

    }

    if-then-else clauses can be (1) Nested and (2) Daisy-chained.

    Find maximum of 3 numbers.

    if (x > y) {if (x > z) {

    max = x;

    } else {

    max = z;

    } else if (y > z) {

    max = y;

    } else {

    max = z;

    }

    switch statements

    switch (month) {

    case2:

    days = 28;

    break;

    case 4:

    case 5:case 6:

    case 7:

    days = 30;

    break;=]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

    default: d

    days = 31;

    break;

    }

    Loops

    public static boolean isPrime(int n) {

    int divisor =2;

    while (divisor < n) {// loop condition

  • 8/11/2019 CS61B Lecture Notes

    10/41

    for (int divisor = 2; divisor < n; divisor ++) {

    if (n% divisor == 0) { //loop body

    return false;

    }

    divisor++;return true;

    }

    for Loops

    for (initialize; condition; next) {

    statements;//equivalent to the following while loop

    }

    initialize;

    while (condition) {

    statements;

    next;

    }

    Arrays

    An object storing a numbered list of variables.

    Each is a primitive type or reference.

    c

    0 1 2 3

    b l u e

    char[] c;//Reference to array (any length) of characters

    c = new char[4];

    c[0] = b;

    .

    .

    .c[3] = e;

    c[4] = s;//run-time error

    Field c.length//you can never assign another value to length compile-

    time error

  • 8/11/2019 CS61B Lecture Notes

    11/41

    Primes Revisited, Sieve of Eratosthenes

    public static void printPrimes(int n) {

    boolean[] prime = new Boolean[n + 1];

    int i;

    for (i = 2, i

  • 8/11/2019 CS61B Lecture Notes

    12/41

    public static int[][] pascalTriangle(int n) {

    int[][] pt = new int[n][];

    for (int i = 0; i < n; i++) {

    pt[i] = new int[i+1];

    pt[i][0] = 1;for (int j = 1; j < I; j++) {

    pt[i][j] = pt[i-1][j-1] + pt[i-1][j];

    }

    pt[i][i] = 1;

    }

    return pt;

    }

  • 8/11/2019 CS61B Lecture Notes

    13/41

    CS61B Lecture 4 (2/3) 9/15/2014 12:31:00 PM

    Automatic Array Construction

    int [][] table = new int[x][y];

    constructs an array of x references to arrays.

    constructs x arrays of y int

    InitializersHuman[] b = {amanda, rishis, new Human(Paolo)};

    int[][] c = {{7, 3, 2}, {x}, {8, 5, 0, 0}, {y+z, 3}};

    d = {3, 7}; //doesnt compile

    f({1, 2, 3});//doesnt compile

    int[] a, b, c; //All reference arrays

    int a[], b, c[][];//a is 1d, c is 2d, b is not array

    int[] a, b[];//a is 1d, b is 2d

    int[] b[] = new int[3][];

    int[] b[] = new int[][3];//doesnt compile

    Arrays of Objects

    When you construct array of objects, Java does not construct the

    objects.

    Do Loop

    do alwaysexecutes at least one loop.

    the while condition goes at the end.

    Loops

    break only breaks out of the local switch statement

    continue

    o only applies to loops

    o jumps to end of loop body but another iteration commences if

    loop condition satisfied.

    continue in a for loop will fulfill increment or refreshing condition

    but will not in a while loop (last example on Lecture 6 handout.

    Constants

    final keyword: value that can never be changed.

    o BAD: if (month == 2) { ...

    o GOOD: public final static int FEBRUARY = 2;

  • 8/11/2019 CS61B Lecture Notes

    14/41

    .

    .

    .

    o For any array x, x.length is a final field.

  • 8/11/2019 CS61B Lecture Notes

    15/41

    CS61B Discussion 2 (2/5) 1/22/2014 11:30:00 PM

    Method Signature

    Name of the method

    Number, type, order of parameters

    Method Prototype

    Method signature Return types

    Access modifiers (public, private, static)

    Method Overloading

    2 or more methods of the same name, but different signatures

    o e.g. the print method

    println(String s);

    println(int n);

    Short Circuit

    &&: if statement 1 is false, statement 2 not evaluated

    ||: if statement 1 is true, statement 2 not evaluated

    && short circuits, & evaluates all

    Break and Continue

    breakjumps to end of labeled enclosure, loop, switch statements,

    if/else

    continuecan only be used with loops and jumps to the end of the

    current iteration

  • 8/11/2019 CS61B Lecture Notes

    16/41

    CS61B Lecture 5 (2/5) 1/22/2014 11:30:00 PM

    Announcement

    HKN drop in tutoring: 290 Cory, 395 Soda

    Array-based Lists

    Advantage: very fast access to any particular item 2 disadvantages:

    o inserting item at beginning or middle of the list will shift every

    item after it one space over --> takes time proportional to

    length of array

    o Array has a fixed length.

    public class List {

    int[] a;

    int lastItem;

    public List() {

    a = new int[10];

    lastItem = -1

    }

    public void insertItem(int newItem, int location) {

    int i;

    if (lastItem + 1) == a.length) {//resize length of the array

    int[] b = new int[2 * a.length];//doubles length

    for (i=0; i = location; i--) { //shuffle over every

    element over to make space for inserted item

    a[i + 1] = a[i];

    }

    a[location] = newItem;

  • 8/11/2019 CS61B Lecture Notes

    17/41

    lastItem ++;

    }

    }

    Linked Lists(a recursively data type) Made up of nodes. Each node has:

    o An item (car)

    o Reference to the next node in the list (cdr)

    public class ListNode {

    public int item;

    public ListNode next;

    }

    ListNode l1 = new ListNode(), l2 = new ListNode(), l3 = new ListNode();

    //this code in another place

    l1.item = 1;//create a ListNode object

    l2.item = 0;//create a ListNode object

    l3.item = 6;//create a ListNode object

    l1.next = l2;//links l2 to l1

    l2.next = l3;//links l3 to l2

    l3.next = null;//does this by default in Java, but necessary in C and C++,so initialize memory to develop good habit.

    Shorting the code for ListNode:

    public ListNode(int i, ListNode n) {

    item = i;

    item = n;

    }

    public ListNode(int i) {

    this(i, null);

    }

    ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(5)))

    Linked lists vs. array lists

  • 8/11/2019 CS61B Lecture Notes

    18/41

    Advantages of linked lists:

    o Inserting item into middle of linked list takes constant time, if

    you have a reference to previous node.

    o List can keep growing until memory runs out.

    Insert a new item:

    public void insertAfter(int item) {

    next = new ListNode(item, next);//the first next replaces the old

    next, the second next is the old next

    }

    Disadvantage of linked list: Finding nthitem of a linked list take

    time proportional to n.

    Start at head, walk n-1 nodes.

    Lists of Objects

    reference object by using the object keyword.

    public class SListNode {

    public Object item;//any object can be put in here.

    public SListNode next;//S stands for singly linked list

    }

    problems with SListNode:

    o Insert new item at beginning of list:

    x = new SListNode(soap, x);//doesnt change other

    references to this list when new item is added

    o How do you represent an empty list?

    x = null;

    x.insertAfter(item);//Run-time error: Null point error

    because you cant call methods on Null

    o Solution: Separate SList class maintain the first node of the

    list(head).

    public class SList {

    private SListNode head;

  • 8/11/2019 CS61B Lecture Notes

    19/41

    private int size;

    public SList() {//solves the problem of roommate grocery (when

    two or more pointers point at the list and the list changes all of the

    pointers wont change to point to the head of the list) by keepingtrack of the head/

    head = null;

    size = 0;

    }

    public void insertFront(Object Item) {

    head = new SListNode(item, head);

    size++;

    }

    }

    The public and private keywords

    private method or field

    o invisible and inaccessible to other classes

    o can only be used in the field/class in which it was declared

    why have private variables?

    o

    to prevent data from being corrupted by other classes.o abstraction barrier! (gives you freedom later on to improve

    your implementation without causing other classes to fail.

    The interface of a class

    prototypes for public methods (Java code)

    description of their behaviors (plain English)

    Abstract Date Type (ADT)

    A class with well-defined interface, but implementation details are

    hidden from other classes.

    invariance

    o A fact about a data structure that is always true

    e.g. the Dateobject always stores a valid date.

    o Enforced by allowing access only through method calls.

  • 8/11/2019 CS61B Lecture Notes

    20/41

    Not all classes are ADTs! Some classes are nothing more than data storage

    units. No invariants; fields can be public.

    The SList ADT Another advantage of SList class: it enforces 2 invariants

    o size is always correct.

    o A list is never circularly linked (there should always be a tail

    node)

    Both goals can be accomplished because onlySList methods can

    change the lists. SList ensures this:

    o the fields of SList (head and size) are private.

    o No method of SList returns an SListNode (this will change this

    in a week or two).

    Doubly linked lists

    Inserting/deleting at frontof list is easy.

    Inserting/deleting at the endof the list takes a long time.

    o this is because you have to start at the head of the list and go

    through all the nodes to get to the end.

    Two features:

    o

    Keep track of the tail of the list (as well as the head)o Linked in the opposite directional (as well as the original

    direction)

    class DListNode {

    Object item;

    DListNode next;

    DListNode prev;

    }

    class DList {

    private DListNode head;

    private DListNode tail;

    long size;

    }

  • 8/11/2019 CS61B Lecture Notes

    21/41

    DList inserts and deletes items at both ends in constant running

    time.

    Removing the tail node (at least 2 items in DList):

    tail.prev.next = null;tail = tail.prev;

    Slightly different Dlist representation

    designate one note to be a Sentinel, a special node that does not

    represent an item.

    DList with Sentinel are linked in a circle

    class DListNode {

    Object item;

    DListNode next;

    DListNode prev;

    }

    class DList {

    private DListNode head;

    private DListNode tail;

    long size;}

    DList invariants (With sentinel):

    For any DList d,d.head != null

    For any DListNode x,x.prev != null

    For any DListNode x,x.next != null

    For any DListNode x,ifx.next == y, then y.prev == x.

    A DLists size variable is # of DListNodes, not counting sentinel,

    accessible from sentinel by sequence of next s.

    public long size() {

    return size;

    }

  • 8/11/2019 CS61B Lecture Notes

    22/41

    Empty DList

    o Sentinels prev and next field point to itself.

    public void removeBack() {

    if head.prev != head {//changes tailhead.prev = head.prev.prev;

    head.prev.next = head;

    size--;

    }

    }

  • 8/11/2019 CS61B Lecture Notes

    23/41

    CS61B Lecture 6 (2/10) 1/22/2014 11:30:00 PM

    Where does Java store your code?

    Heap

    o the heap stores all objects including all arrays and all class

    variables

    Stacko the stackstores all local variables, including parameters

    When a method is called, Java creates a stack frame (aka activation

    record); stores the parameters and local variables

    the top stack frame is the frame that is running. All other frames

    must wait for all frames above them to execute.

    when a method finishes, its stack frame is erased and all the local

    variables it points to are also erased.

    Thread.DumpStack() prints stack. Helpful for debugging

    Parameter Passing

    Java passes all parameters by value: copied

    class IntBox {

    static void doNothing(int x) {

    x = 2;

    }

    public int i;

    static void set3(IntBox ib) {

    ib.i = 3;

    }

    /**when parameter is a reference, the reference is copied, but the

    object is shared.*/

    static void badSet4(IntBox ib) {

    ib = new IntBox();

    ib.i = 4;

    }

    }

  • 8/11/2019 CS61B Lecture Notes

    24/41

    Example of method calls:

    #1

    int a = 1;doNothing(a);/**this will do nothing because there is no return statement

    or anything */

    #2

    IntBox b = new IntBox();

    set3(b);/**instead of passing the parameter itself, pass in a reference that

    is pointing at the object itself. By doing so, you can change the object*/

    #3

    badSet4(b);/**common programming error! When you create new object in

    the top stack, when the top stack is finished and garbage collected, the new

    object will be garbage collected as well.*/

    Recursion and Stacks: Binary Search Algorithm

    /**searches a sorted array*If we find findMe, return its array index;

    *otherwise, return FAILURE.

    *----------------------------------------------------

    *Recursion base cases:

    *1. findMe == middle element: return its index.

    *2. Subarray of length zero: return FAILURE

    **/

    public static final int Failure = -1;/**array index can never be -1 so thats

    why its okay for Failure = -1**/

    private static int bsearch(int[] i, int left, int right, int findMe) {

    if (left > right) {/**Base Case 2**/

    return Failure;

  • 8/11/2019 CS61B Lecture Notes

    25/41

    }

    int mid = (left + right)/2;/**Middle**/

    if (findMe == i[mid]) { /**Base case1: success!**/

    return mid;

    } else if (findMe < i[mid]) {return bsearch(i, left, mid-1, findMe);

    } else {

    return bsearch(i, mid+1, right, findMe);

    }

    }

    public static int bsearch(int[] i, int findMe) {

    bsearch(i, o, i.length -1, findMe);/**this is always how you start a

    binary search**/

    }

    Enough stack space for few thousand stack frames.

  • 8/11/2019 CS61B Lecture Notes

    26/41

    CS61B Lecture 7 (2/12) 1/22/2014 11:30:00 PM

    Inheritance

    public class TailList extends Slist{

    //head and size inherited from SList

    private SListNode tail;

    //declaring a new field variable

    TailList is a subclass of SList.

    SList is the superclass of TailList.

    A subclass can modify a superclass in 3 ways:

    o it can declare new fields

    o it can declare new methods

    o it can override old methods with new implementations.

    public void insertEnd(Object obj) {

    //* Your solution to Lab3

    }

    isEmpty(), length(), nth(), toString() are all inherited from SList

    with no changes.

    Inheritance and Constructors

    Java executes TailList constructor, which calls SList() constructorbeforeit executes any code.

    public TailList(/**zero-parameter constructor called by default*/) {

    //SList() sets size = 0, head = null, tail = null

    tail = null;

    }

    public TailList(int x) {

    super(x);//must be first statement in constructor

    tail = null;

    }

    Invoking Overridden Methods

  • 8/11/2019 CS61B Lecture Notes

    27/41

    public void insertFront(Object obj) {

    super.insertFront(obj);//super reference same as this

    if (size == 1) {

    tail = head;

    }}

    The protected keyword

    protected means that all subclasses can access the variable but to

    everything else it is private

    private fields are not visible to subclasses.

    public class SList {

    protected SListNode head;

    protected int size;

    .

    .

    .

    }

    Dynamic Method Lookup

    !!!Every TailList ISand SList!!!

    SList s = new TailList();

    TailList t = new SList();//Compile-time error! not all SLists are TailLists

    Static type: the type of a variable

    Dynamic type: the class of the object the variable references.

    When we invoke overridden method, Java calls for the methods

    dynamic type, regardless of static type

    example of dynamic lookup:

    SList s = new TailList();

    s.insertEnd(obj);//calls TailList.insertEnd()

    s = new SList();

  • 8/11/2019 CS61B Lecture Notes

    28/41

    s.insertEnd(obj);//calls Slist.insertEnd()

    WHY DYNAMIC METHOD LOOKUP MATTERS

    Method that sorts an SList using only SList method calls now sorts

    TailLists too

    Subtleties of Inheritance

    1. New method in TailList = eatTail()

    TailList t = new TailList();

    t.eatTail();

    SList s = newTailList();

    s.eatTail()//compile-time ERROR not every SList has an eatTail()

    method: Java cannot use dynamic method lookup on s

    2.

    SList s;

    TailList t = new TailList();

    s = t;//ok

    t = s;//Compile-time ERROR

    //you need a cast to tell Java that you know what youre doing.

    t = (TailList) s;

    s = new SList();//ok

    t = (TailList) s;//Run-time error: ClassCastException

    int x = t.nth(1).intValue();//Compile-time ERROR

    int y ((Integer) t.nth(1)).intValue();

    equals()

    Every class has an equals()method.

    Default: inherit Object.equals()

    r1.equals(r2)same as r1 == r2

    if r1 is null, you will get a run-time error.

    Four degrees of equality:

  • 8/11/2019 CS61B Lecture Notes

    29/41

    o reference equality, ==

    o Shallow structural equality; fields are ==

    o Deep structural equality (tests equality of content), fields are

    .equals()

    o

    Logical equality (meaning of data structure) Set objects are equals if they contain same

    elements (even in different orders)

    Fractions 1/3 and 2/6 are equals

    o equals() may test any of these

    public class SList {

    public boolean equals(Object other) {

    if (!(other instance SList)) {

    return false;

    }

    SList o = (SList) other;

    if (size != 0.size) {

    return false;

    }

    SListNode n1 = head;

    SListNode n2 = o.head;

    while (n1 != null) {if (!n1.item.equals(n2.item)) {

    return false;

    }

    }

    n1 = n1.next;

    n2 = n2.next;

    }

    return true;

    }

    for each LOOPS

    Iterates through array elements.

    int[] array = {7, 12, 3, 8, 4, 9};

  • 8/11/2019 CS61B Lecture Notes

    30/41

    for(int i: array) {//decleration must be in the for loop

    System.out.println(i + );

    }

    i is notiterating from 0 to 5.

    i is taking on values 7, 12, 3, ...

    Testing

    Modular Testing

    o Test drivers and stubs

    Test drivercall the code, check results

    Stubs:Bits of code called by the code being tested.

    Integral Testing

    o Testing all componets together.

    o Define interfaces well.

    o Learn to use a debugger.

    Result Verification

  • 8/11/2019 CS61B Lecture Notes

    31/41

    CS61B Lecture 8 (2/24) 1/22/2014 11:30:00 PM

    Abstract Classes

    a class whose sole purpose is to be extended.

    example:

    //a general interface for lista public abstract class List {

    protected int size;

    public int length() {

    return size;

    }

    public abstract void insertFront(Object item);/**dont provide an

    implementation for insertFront yet but will be implement later in a

    subclass**/

    }

    List myList; //good

    myList = new List(); //Compile time error

    Abstract method lacks an implementation.

    public static SList extends List {

    //inherits size

    protected SListNode head;

    //inherits length()

    public void insertFront(Object item) {

    head new SListNode(item, head);

    size++;

    }

    }

    A non-abstract class may never contain an abstract method

    inherit an abstract method without providing an implementation

    List myList = new SList();//good

  • 8/11/2019 CS61B Lecture Notes

    32/41

    myList.insertFront(obj);//good, compiles because every List has an

    insertFront method.

    An abstract class lets you define an interface

    for multiple classes to share, without defining any of them yet.

    With an abstract data type, one List Sorter can sort every kind of List.

    List Sorter:public void listSort(List l) {...}

    List Sorter --> calls --> List ADT

    subclasses of List: SList, DList, TailList

    TimedList: records time spent on operations.

    TransactionList: logs all changes on a disk.

    The application, not the list sorter, chooses what kind of list is used.

    Java Interfaces

    interface: public fields, method prototypes, and behaviors.

    Java interface : interface keyword.

    Java interface is like abstract class. 2 differences:

    o A class can inherit from only one class. Can implement

    (inherit from) many Java interfaces.

    o A Java interface cannot

    implement any methods,

    include any fields except for final static constants.

    Only contains method prototypes and constants.

    public interface Nukeable {//in Nukeable.java

    public void nuke();//

  • 8/11/2019 CS61B Lecture Notes

    33/41

    }

    public class SList extends List implements Nukeable. Comparable {

    //[previous stuff]

    public void nuke() {

    head = null;size = 0;

    }

    public int compareTo(Object o) {

    //[Returns a number < 0 if this < 0,

    0 if this.equals(0),

    > 0 if this > 0.]

    }

    }

    Nukeable n = new SList();

    Comparable c = (Comparable) n;//need a cast because not every Nukeable

    is a Comparable.

    //Arrays class in java.util sorts arrays of comparable objects.

    public static void sort(Object[] a);

    A subinterface can have multiple superinterfaces.

    public interface NukeAndCompare extends Nukeable, Comparable {}//Dont

    need to add anything so dont need anything in the braces {}

    Java Packages

    package

    o

    collection of classes, Java interfaces & subpackages that trusteach other. 3 benefits:

    packages can contain hidden classes that are only

    visible in the packages.

    classes can have fields & methods visible inside package

    only.

  • 8/11/2019 CS61B Lecture Notes

    34/41

    Different packages can have classes with the same

    name.

    java awt.Frame photo.Frame

    Examples java.io

    Homework 4 uses list package containing DList & DListNode.

    o java.awt.image.Model

    Using Packages

    Fully-qualified name

    o java.lang.System.out.println( );

    import java.io.File;//can now refer to File.

    Every program imports java.lang.*

    x.y.z.Class //

  • 8/11/2019 CS61B Lecture Notes

    35/41

    Iterators

    public interface Iterator {

    boolean hasNext();

    Object next();void remove();//optional

    }

    An Iterator is like a boomark.

    can have many Iterators in same data structure.

    Calling next() nthtime returns nthitem in sequence.

    Subsequent calls to next() throw an exception.

    hasNext(); returns true if more items to return.

    should always call hasNext()before calling next().

    DS.iterate() constructs a DSIterator for DS. (DS implements the Iterable

    class).

    for each loop iterates over item in data structure.

    for (Object o : l) {

    System.out.println(o);

    }equivalent to:

    for (Iterator i = l.iterator(); i.hasNesxt();) {

    Object o = i.next();

    System.out.println(o);

    }

  • 8/11/2019 CS61B Lecture Notes

    36/41

    CS61B Lecture 9 (2/26) 1/22/2014 11:30:00 PM

    Exceptions

    Run-time error: Java throws an exception (Exception object)/ Preventthe

    error by catching the Exception.

    Purpose #1: Coping with errors.

    try {

    f = new FileInputStream(~cs61b/pj2.solution);

    i = f.read();

    }

    catch(FileNotFoundException e1) {/**declare variable e1

    FileNotFoundException type, which is a subclass of Exception**/

    System.out.println(e1);//Exception handler

    }

    catch(IOException e2) {//variable declaration

    f.close();//Exception handler

    a. }

    1. excecutes the code inside try clause

    2. If try code executes normally, skip catchclauses.

    3. If try code throws an exception, do not finish try code,

    jump to first catch clause that matches the exception;excecutes code inside that catch clause. matches: exception

    object thrown is same class/subclass of type in catch

    clause.

    Purpose #2: Escaping a Sinking Ship

    throw your own exception

    public class ParserException extends Exception {}/**distinguishable from

    other types of exceptions**/

    public ParseTree parse Expression() throws ParserException {

    //very complicated code here

    if (somethingWrong) {

    throw new Parser Exception();

    }

  • 8/11/2019 CS61B Lecture Notes

    37/41

    //more complicated code here

    }

    Different from return?

    Dont return anything.

    An exception can propagate several stack frames down the stack.o propagates down until it means it finds a method that catches

    the exception

    o propagates until the end where it will crash the program.

    public void compile() {

    Parse p;

    try {

    p = parse();

    p.toByteCode();

    }

    catch(ParserException e1) {}

    catch (DumbCodeException e2) {}

    e.printStrackTrace();

    }

    errors can be thrown because they are a subclass ofThrowable but you

    probably do not want to catch them since they are pretty bad.

    RunTimeException is usually thrown by Java and not by the coder.

    unchecked exceptions are exceptions that any method can throw (such as

    NullPointerException, ClassCastException, AssertionError, etc.).

    All exceptions except RunTimeExceptions are checked.

    When a method calls a method that can throw a checked exception,

    1. It can catch the exception, or

    2. It throws same exception itself.

    thefinally keyword

  • 8/11/2019 CS61B Lecture Notes

    38/41

    f = new FileInputStream(filename);

    try {

    statement X;

    return 1;

    } catch (IOException e) {e.printStackTrace();/**When exception is constructed, it takes a

    snapshot of stack**/

    return 2;

    } finally {

    f.close();

    }

    If try statement begins, the finally clause will execute at the end, no

    matter what!

    If statement X causes no exception --> finally clause executed, returned.

    If statement X causes IOException --> catch clause executes, then execute

    the finally clause.

    If statement X causes some other exception --> finally clause excecutes,then the exception continues down the stack.

    Exception thrown in catch clause: terminate the catch clause, execute

    finally, exception.

    Exception thrown in finally clause: replace old exception, finally clause

    and method end.

    Exception constructors

    convention: Most Throwables have 2 constructors.

    class MyException extends Exception {

    public MyException(){ super(); }

  • 8/11/2019 CS61B Lecture Notes

    39/41

    public MyException(String s) { super(s); }/**String s is an error

    message**/

    }

    Error message: printed if it propagates out of main().

    can be read by Throwable.getMessage().

  • 8/11/2019 CS61B Lecture Notes

    40/41

    GENERICS (2/26) 1/22/2014 11:30:00 PM

    Declare general classes that produce specialized objects.

    SList for Strings, SList for Integers, only one SList class.

    SList takes a type parameter.

    class SListNode {Titem;

    SListNode next;

    SListNode(Ti, SListNode n) {

    item = i;

    next = n;

    }

    }

    public class SList {//formal type parameter is T

    SListNode head;

    public void insertFront(Titem) {

    head = new SListNode(item, head);

    }

    }

    Create an SList of Strings:

    SList l = new SList();/**actual type parameter is

    String**/

    l.insertFront(Hello);String s = l.front().item();

    Advantages:

    compile ensures at compile time that nothing can but Strings can

    get into your SList

    Field Shadowing

    fields can be shadowed in subclasses.

    Very different from overriding methods.

    Choice of method dictated by dynamic type.

    Choice of fields dictated by the static type.

    class Super {

    int x = z

  • 8/11/2019 CS61B Lecture Notes

    41/41

    int f() {

    return 2;

    }

    }

    class Sub extends Super {

    int x = 4;//shadows Super.x

    int f() {//overrides Super.f()

    return 4;

    }

    }

    Sub sub = new Sub();

    Super supe = sub;

    int i;

    i = supe.x;//i is 2

    i = sub.x;//i is 4

    i = ((Super) sub).x//i is 2

    i = ((Sub) supe).x//i is 4

    i = supe.f();//i is 4

    i = sub.f();//i is 4

    i = ((Super)).sub.f();//i is 4i = ((Sub) supe).f();//i is 4

    void g() {

    int i;

    i = this.x;//i is 4

    i = (Super) this).x;//i is 2

    i = super.x;//i is 2

    }