CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs)

Slides:



Advertisements
Similar presentations
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Advertisements

CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Building Java Programs Chapter 16 Linked Lists. 2 A swap method? Does the following swap method work? Why or why not? public static void main(String[]
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 slides created by Marty Stepp
Building Java Programs Interfaces, Comparable reading: , 16.4, 10.2.
CSE 143 Lecture 15 Sets and Maps; Iterators reading: ; 13.2; 15.3; 16.5 slides adapted from Marty Stepp
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-4: Interfaces reading: self-check: exercises: #11.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 9 Interfaces; Stacks and Queues slides created by Marty Stepp
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh) reading: 9.5, 11.1, slides created by Marty Stepp
EE 422C Interfaces Day 5. 2 Announcements SVN has Project 2. –Partly due next week. –SVN update to get it in your repository. See Piazza for Grocery List.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
CSE 143 Lecture 12: Sets and Maps reading:
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 16 Iterators; Grammars reading: 11.1, 15.3, 16.5 slides created by Marty Stepp
Building Java Programs Interfaces reading: , 16.4.
Slides by Donald W. Smith
Lecture 21: Interfaces and Abstract classes
Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2
Sixth Lecture ArrayList Abstract Class and Interface
Building Java Programs Chapter 16
CSE 373 Implementing a Stack/Queue as a Linked List
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets
Building Java Programs
Interfaces.
Building Java Programs Chapter 16
A tree set Our SearchTree class is essentially a set.
Lecture 1: Welcome to CSE 373
Interfaces EE 422C.
Linked node problem 3 What set of statements turns this picture:
Interfaces CS163 Fall 2018.
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh)
Building Java Programs
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
A tree set Our SearchTree class is essentially a set.
slides adapted from Marty Stepp
CSE 143 Lecture 2 Collections and ArrayIntList
Iteration Abstraction
slides created by Marty Stepp and Hélène Martin
Shapes Consider the task of writing classes to represent 2D shapes such as Circle, Rectangle, and Triangle. Certain operations are common to all shapes:
CSE 373 Java Collection Framework, Part 2: Priority Queue, Map
Binary Search Trees continued; Tree Sets
slides created by Marty Stepp
Lecture 8: Complex Linked List Code reading: 16.2 – 16.3
Building Java Programs Chapter 16
Based on slides by Alyssa Harding & Marty Stepp
CSE 143 Lecture 25 Advanced collection classes
JCF Collection classes and interfaces
Binary search (13.1) binary search: Locates a target value in a sorted array/list by successively eliminating half of the array from consideration. How.
CSE 143 Lecture 3 Implementing ArrayIntList reading:
CSE 373 Implementing a Stack Reading: Weiss Ch. 3; 3.6; 1.5
slides created by Alyssa Harding
Lecture 20: Interfaces and Abstract classes
slides created by Alyssa Harding
CSE 143 Lecture 15 Sets and Maps; Iterators reading: ; 13.2
slides adapted from Marty Stepp
Building Java Programs
slides created by Marty Stepp
CSE 143 Lecture 8 Iterators; Comparable reading: 11.2; 10.2
Lecture 7: Linked List Basics reading: 16.2
CSE 143 Lecture 6 interfaces; eclipse; testing
Iterators Dan Fleck.
CSE 143 Lecture 21 Advanced List Implementation
slides created by Marty Stepp
slides created by Marty Stepp and Hélène Martin
Presentation transcript:

CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 slides adapted from Marty Stepp and Hélène Martin http://www.cs.washington.edu/143/

Consider classes for shapes with common features: Related classes Consider classes for shapes with common features: Circle (defined by radius r ): area =  r 2, perimeter = 2  r Rectangle (defined by width w and height h ): area = w h, perimeter = 2w + 2h Triangle (defined by side lengths a, b, and c) area = √(s (s - a) (s - b) (s - c)) where s = ½ (a + b + c), perimeter = a + b + c Every shape has these, but each computes them differently. r w h a b c

Interfaces (9.5) interface: A list of methods that a class can promise to implement. Inheritance gives you an is-a relationship and code sharing. A Lawyer can be treated as an Employee and inherits its code. Interfaces give you an is-a relationship without code sharing. A Rectangle object can be treated as a Shape but inherits no code. Analogous to non-programming idea of roles or certifications: "I'm certified as a CPA accountant. This assures you I know how to do taxes, audits, and consulting." "I'm 'certified' as a Shape, because I implement the Shape interface. This assures you I know how to compute my area and perimeter."

Interface syntax public interface name { public type name(type name, ..., type name); ... } Example: public interface Vehicle { public int getSpeed(); public void setDirection(int direction);

Shape interface abstract method: A header without an implementation. // Describes features common to all shapes. public interface Shape { public double area(); public double perimeter(); } Saved as Shape.java abstract method: A header without an implementation. The actual bodies are not specified, because we want to allow each class to implement the behavior in its own way.

Implementing an interface public class name implements interface { ... } A class can declare that it "implements" an interface. The class must contain each method in that interface. public class Bicycle implements Vehicle { (Otherwise it will fail to compile.) Banana.java:1: Banana is not abstract and does not override abstract method area() in Shape public class Banana implements Shape { ^

Interfaces + polymorphism Interfaces benefit the client code author the most. They allow polymorphism. (the same code can work with different types of objects) public static void printInfo(Shape s) { System.out.println("The shape: " + s); System.out.println("area : " + s.area()); System.out.println("perim: " + s.perimeter()); System.out.println(); } ... Circle circ = new Circle(12.0); Triangle tri = new Triangle(5, 12, 13); printInfo(circ); printInfo(tri);

Linked vs. array lists We have implemented two collection classes: ArrayIntList LinkedIntList They have similar behavior, implemented in different ways. We should be able to treat them the same way in client code. index 1 2 3 value 42 -3 17 9 data next 42 data next -3 data next 17 data next 9 front

An IntList interface // Represents a list of integers. public interface IntList { public void add(int value); public void add(int index, int value); public int get(int index); public int indexOf(int value); public boolean isEmpty(); public void remove(int index); public void set(int index, int value); public int size(); } public class ArrayIntList implements IntList { ... public class LinkedIntList implements IntList { ...

Client code w/ interface public class ListClient { public static void main(String[] args) { IntList list1 = new ArrayIntList(); process(list1); IntList list2 = new LinkedIntList(); process(list2); } public static void process(IntList list) { list.add(18); list.add(27); list.add(93); System.out.println(list); list.remove(1);

ADTs as interfaces (11.1) abstract data type (ADT): A specification of a collection of data and the operations that can be performed on it. Describes what a collection does, not how it does it. Java's collection framework uses interfaces to describe ADTs: Collection, Deque, List, Map, Queue, Set An ADT can be implemented in multiple ways by classes: ArrayList and LinkedList implement List HashSet and TreeSet implement Set LinkedList , ArrayDeque, etc. implement Queue They messed up on Stack; there's no Stack interface, just a class.

When using Java's built-in collection classes: Using ADT interfaces When using Java's built-in collection classes: It is considered good practice to always declare collection variables using the corresponding ADT interface type: List<String> list = new ArrayList<String>(); Methods that accept a collection as a parameter should also declare the parameter using the ADT interface type: public void stutter(List<String> list) { ... }

Iterators reading: 11.1; 15.3; 16.5

Examining sets and maps elements of Java Sets and Maps can't be accessed by index must use a "foreach" loop: Set<Integer> scores = new HashSet<Integer>(); for (int score : scores) { System.out.println("The score is " + score); } Problem: foreach is read-only; cannot modify set while looping if (score < 60) { // throws a ConcurrentModificationException scores.remove(score);

Iterators (11.1) iterator: An object that allows a client to traverse the elements of any collection. Remembers a position, and lets you: get the element at that position advance to the next position remove the element at that position "the" "to" "from" "we" index 1 2 3 4 5 6 7 8 9 value 12 size set list current element: 9 current index: 2 iterator current element: "from" next element: "the" iterator

Iterator methods Iterator interface in java.util every collection has an iterator() method that returns an iterator over its elements Set<String> set = new HashSet<String>(); ... Iterator<String> itr = set.iterator(); hasNext() returns true if there are more elements to examine next() returns the next element from the collection (throws a NoSuchElementException if there are none left to examine) remove() removes the last value returned by next() (throws an IllegalStateException if you haven't called next() yet)

Iterator example Set<Integer> scores = new TreeSet<Integer>(); scores.add(94); scores.add(38); // Jenny scores.add(87); scores.add(43); // Marty scores.add(72); ... Iterator<Integer> itr = scores.iterator(); while (itr.hasNext()) { int score = itr.next(); System.out.println("The score is " + score); // eliminate any failing grades if (score < 60) { itr.remove(); } System.out.println(scores); // [72, 87, 94]

A surprising example What's bad about this code? List<Integer> list = new LinkedList<Integer>(); ... (add lots of elements) ... for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } data next 42 data next -3 front = data next 17 element 0 element 1 element 2

Iterators and linked lists Iterators are particularly useful with linked lists. The previous code is O(N2) because each call on get must start from the beginning of the list and walk to index i. Using an iterator, the same code is O(N). The iterator remembers its position and doesn't start over each time. data next 42 data next -3 front = data next 17 element 0 element 1 element 2 current element: -3 current index: 1 iterator

ListIterator lists have a more powerful ListIterator with more methods add(value) inserts an element just after the iterator's position hasPrevious() true if there are more elements before the iterator nextIndex() the index of the element that would be returned the next time next is called on the iterator previousIndex() the index of the element that would be returned the next time previous is called on the iterator previous() returns the element before the iterator (throws a NoSuchElementException if there are none) set(value) replaces the element last returned by next or previous with the given value ListIterator<String> li = myList.listIterator(); lists have a more powerful ListIterator with more methods can iterate forwards or backwards can add/set element values (efficient for linked lists)