CS61B Lecture #11: Examples: Comparable & Reader

Similar documents
CS61B Lecture #11: Examples: Comparable & Reader. Last modified: Wed Sep 24 12:44: CS61B: Lecture #11 1

Recreation. Last modified: Mon Sep 21 12:46: CS61B: Lecture #11 1

CS61B Lecture #11: Examples: Comparable & Reader

Recreation. Last modified: Sun Sep 16 17:51: CS61B: Lecture #11 1

CS61B Lecture #11. Please report problems (missing files, malfunctions of submit, etc.) by , not by the newsgroup, for faster service.

CS61B Lecture #8. Last modified: Fri Sep 17 12:18: CS61B: Lecture #8 1

CS 61B Discussion 5: Inheritance II Fall 2014

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

CS61B Lecture #9: Interfaces and Abstract Classes

CS61B Lecture #3. Homework: Please see Homework #1 on the lab page. Last modified: Wed Sep 10 20:34: CS61B: Lecture #3 1

MIT AITI Lecture 18 Collections - Part 1

Note that if both p1 and p2 are null, equals returns true.

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

PIC 20A Number, Autoboxing, and Unboxing

Public-Service Announcement

CS61B Lecture #2. Public Service Announcements:

Lecture 10: Interfaces

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Introduction to Programming Using Java (98-388)

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

University of Palestine. Mid Exam Total Grade: 100

Introduction to Programming (Java) 4/12

(Not Quite) Minijava

Full file at

ITI Introduction to Computing II

I/O streams. Byte Streams Character Streams InputStream ByteArrayInputStream FileInputStream FilterInputStream

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

CS61B Lecture #13: Packages, Access, Etc.

Public-Service Announcement

Introduction to Inheritance

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

Public-Service Announcement

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

DO NOT. package java.lang; public final class String implements Serializable, Comparable, CharSequence {

Generic BST Interface

1B1b Classes in Java Part I

Java and OOP. Part 5 More

Error Handling. public int divide(double a, double b) { if (b==0) return -1; // error double result = a/b; return 0; // success }

Name CIS 201 Midterm II: Chapters 1-8

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

CSci 4061 Introduction to Operating Systems. IPC: Basics, Pipes

CS61B Lecture #5: Arrays and Objects

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington

CSci 4061 Introduction to Operating Systems. IPC: Basics, Pipes

Outline. More optimizations for our interpreter. Types for objects

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

ITI Introduction to Computing II

ITI Introduction to Computing II

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

CS61B Lecture #13: Packages, Access, Etc.

ECE 122. Engineering Problem Solving with Java

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

CS61B Lecture #14: Integers. Last modified: Wed Sep 27 15:44: CS61B: Lecture #14 1

Today: Sorting algorithms: why? Insertion Sort. Inversions. CS61B Lecture #26. Last modified: Wed Oct 24 13:43: CS61B: Lecture #26 1

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Super-Classes and sub-classes

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

CS61B Lecture #12. Public Service Announcement. Miscellaneous Topics: What to do About Errors? throw new SomeException (optional description);

Instructions. This exam has 7 questions, worth 10 points each. You have 50 minutes.

CS61B Lecture #9: Interfaces and Abstract Classes. Recreation. Abstract Methods and Classes. Methods on Drawables

Records. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05

CS61B Lecture #9: Abstract Classes and All That

COS 126 General Computer Science Spring Written Exam 1

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

The I/O Package. THE Java platform includes a number of packages that are concerned with the CHAPTER20

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 25, 2016

Principles of Object Oriented Programming. Lecture 4

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer.

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R.

COMP322 - Introduction to C++

CS/ENGRD 2110 FALL Lecture 5: Local vars; Inside-out rule; constructors

Recursive Data and Recursive Functions

CS61B Lecture #8: Object-Oriented Mechanisms

protected BinaryNode root; } 02/17/04 Lecture 11 1

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

CSC 240 Computer Science III Spring 2018 Midterm Exam. Name

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CS 3 Introduction to Software Engineering. 5: Iterators

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Lecture 4: Exceptions. I/O

Maximization and Minimization Problems. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

index.pdf January 21,

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

9 A Preview of.net 2.0

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Principles of Software Construction: Objects, Design and Concurrency. Design Case Study: Stream I/O. toad

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Primitive Java Generic Class

Chapter 13 Abstract Classes and Interfaces

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

Jonathan Aldrich Charlie Garrod

Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p no multiple inheritance with classes

Last class. -More on polymorphism -super -Introduction to interfaces

Transcription:

CS61B Lecture #11: Examples: Comparable & Reader Java library provides an interface to describe Objects that have a natural order on them, such as String, Integer, BigInteger and BigDecimal: public interface Comparable { // For now, the Java 1.4 version /** Returns value <0, == 0, or > 0 depending on whether * THIS is <, ==, or > OBJ. Exception if OBJ not of compatible type. */ int compareto(object obj); Might use in a general-purpose max function: /** The largest value in array A, or null if A empty. */ public static Comparable max(comparable[] A) { if (A.length == 0) return null; Comparable result; result = A[0]; for (int i = 1; i < A.length; i += 1) if (result.compareto(a[i]) < 0) result = A[i]; return result; Nowmax(S)willreturnmaximumvalueinSifSisanarrayofStrings, or any other kind of Object that implements Comparable. Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 1

Examples: Implementing Comparable /** A class representing a sequence of ints. */ class IntSequence implements Comparable { private int[] myvalues; private int mycount;... public int get(int k) { return myvalues[k]; @Override public int compareto(object obj) { IntSequence x = (IntSequence) obj; // Blows up if incomparable for (int i = 0; i < mycount && i < x.mycount; i += 1) if (myvalues[i] < x.myvalues[i]) return -1; else if (myvalues[i] > x.myvalues[i]) return 1; return mycount - x.mycount; // Umm. A bit tricky Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 2

Implementing Comparable II Also possible to add an interface retroactively. If IntSequence did not implement Comparable, but did implement compareto (without @Override), we could write class ComparableIntSequence extends IntSequence implements Comparable { Java would then match up the compareto in IntSequence with that in Comparable. Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 3

Example: Readers Java class java.io.reader abstracts sources of characters. Here, we present a revisionist version (not the real thing): public interface Reader { // Real java.io.reader is abstract class /** Release this stream: further reads are illegal */ void close(); /** Read as many characters as possible, up to LEN, * into BUF[OFF], BUF[OFF+1],..., and return the * number read, or -1 if at end-of-stream. */ int read(char[] buf, int off, int len); /** Short for read(buf, 0, BUF.length). */ int read(char[] buf); /** Read and return single character, or -1 at end-of-stream. */ int read(); Can t write new Reader(); it s abstract. So what good is it? Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 4

Generic Partial Implementation According to their specifications, some of Reader s methods are related. Can express this with a partial implementation, which leaves key methods unimplemented and provides default bodies for others. Result still abstract: can t use new on it. /** A partial implementation of Reader. Complete * implementations MUST override close and read(,,). * They MAY override the other read methods for speed. */ public abstract class AbstractReader implements Reader { public abstract void close(); public abstract int read(char[] buf, int off, int len); public int read(char[] buf) { return read(buf,0,buf.length); public int read() { return (read(buf1) == -1)? -1 : buf1[0]; private char[] buf1 = new char[1]; Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 5

Implementation of Reader: StringReader The class StringReader reads characters from a String: public class StringReader extends AbstractReader { private String str; private int k; /** A Reader delivering the characters in STR. */ public StringReader(String str) { this.str = str; k = 0; public void close() { str = null; public int read(char[] buf, int off, int len) { if (k == str.length()) return -1; len = Math.min(len, str.length() - k); str.getchars(k, k+len, buf, off); k += len; return len; Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 6

Using Reader Consider this method, which counts words: /** The total number of words in R, where a "word" is * a maximal sequence of non-whitespace characters. */ int wc(reader r) { int c0, count; c0 = ; cnt = 0; while (true) { int c = r.read(); if (c == -1) return count; if (Character.isWhitespace((char) c0) &&! Character.isWhitespace((char) c)) count += 1; c0 = c; This method works for any Reader: // Number of words in the String sometext: wc(new StringReader(someText)) // Number of words in standard input. wc(new InputStreamReader (System.in)) // Number of words in file named filename: wc(new FileReader(fileName)) other implementations of Reader Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 7

How It Fits Together Client Interface Concrete Class Abstract Template Reader StringReader AbstractReader read(b,o,l) read(b,o,l) overrides read(b,o,l) wc method read() calls read(b) read() which is really read(b) read() calls inherited from calls inherited from read(b) read() implements extends implements Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 8

Lessons TheReader interface class served as a specification for a whole set of readers. Ideally, most client methods that deal with Readers, like wc, will specify type Reader for the formal parameters, not a specific kind of Reader, thus assuming as little as possible. AndonlywhenaclientcreatesanewReaderwillitgetspecificabout what subtype of Reader it needs. That way, client s methods are as widely applicable as possible. Finally, AbstractReader is a tool for implementors of non-abstract Reader classes, and not used by clients. Alas, Java library is not pure. E.g., AbstractReader is really just called Reader and there is no interface. In this example, we saw what they should have done! The Comparable interface allows definition of functions that depend only on a limited subset of the properties (methods) of their arguments (such as must have a compareto method ). Last modified: Wed Sep 19 14:56:29 2012 CS61B: Lecture #11 9