COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

Similar documents
Java Comparable interface

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

COMP 250. inheritance (cont.) interfaces abstract classes

EXAMINATIONS 2016 TRIMESTER 2

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

For this section, we will implement a class with only non-static features, that represents a rectangle

EXAMINATIONS 2017 TRIMESTER 2

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms

Java Collection Framework

COMP 103 Introduction to Data Structures and Algorithms

Outline. iterator review iterator implementation the Java foreach statement testing

13 A: External Algorithms II; Disjoint Sets; Java API Support

Announcements HEAPS & PRIORITY QUEUES. Abstract vs concrete data structures. Concrete data structures. Abstract data structures

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

COMP 250. Lecture 6. doubly linked lists. Sept. 20/21, 2017

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

[TAP:PMUHE] Stack vs Queue

Java Review: Objects

Collections, Maps and Generics

Interfaces. An interface defines a set of methods. An interface declaration contains signatures, but no implementations.

doubly linked lists Java LinkedList

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Data Structures Brett Bernstein

Polymorphism: Interfaces and Iteration. Fundamentals of Computer Science

PIC 20A Collections and Data Structures

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Java Collections Framework reloaded

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017

MIT AITI Lecture 18 Collections - Part 1

CSE 143 Lecture 20. Circle

Computer Science II (Spring )

HEAPS & PRIORITY QUEUES

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

EXAMINATIONS 2006 SUMMER TRIMESTER. COMP103 Introduction to Data Structures and Algorithms

Domain-Driven Design Activity

Chapter 21- Using Generics Case Study: Geometric Bunch. Class: Driver. package csu.matos; import java.util.arraylist; public class Driver {

Collections Questions

Collections (Java) Collections Framework

Lecture 8: Iterators and More Mutation

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

CMSC132 Summer 2018 Midterm 1

Solution to Test of Computer Science 203x Level Score: / 100 Time: 100 Minutes

Pieter van den Hombergh Richard van den Ham. February 8, 2018

CS11 Java. Winter Lecture 8

CS 314 Final Fall 2011

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

ITI Introduction to Computing II

Practical Session 3 Java Collections

MIDTERM EXAM THURSDAY MARCH

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

Computational Expression

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

CMSC132 Summer 2018 Midterm 1. Solution

182 review 1. Course Goals

CS 310: Maps and Sets

Software 1 with Java. Recitation No. 6 (Collections)

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Interfaces. Relatedness of types. Interface as a contract. The area and perimeter of shapes 7/15/15. Savitch ch. 8.4

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

Introduction to Computer Science I

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

CS 307 Final Spring 2010

CS61BL: Data Structures & Programming Methodology Summer 2014

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

Topic 10: The Java Collections Framework (and Iterators)

Interfaces and itera-on. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

Model Solutions. COMP 103: Test April, 2013

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Linked List Nodes (reminder)

Model Solutions. COMP 103: Test May, 2013

Class 32: The Java Collections Framework

Chapter 6: Inheritance

Points off Total off Net Score. CS 314 Final Exam Spring 2017

CMSC132, Practice Questions

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

CONTAİNERS COLLECTİONS

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Name Section Number. CS210 Exam #4 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

ITI Introduction to Computing II

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

ITI Introduction to Computing II

Java Collections Framework

Transcription:

COMP 250 Lecture 32 interfaces (Comparable, Iterable & Iterator) Nov. 22/23, 2017 1

Java Comparable interface Suppose you want to define an ordering on objects of some class. Sorted lists, binary search trees, priority queues all require that an ordering exists. (Elements are comparable ). 2

Comparable interface interface Comparable<T> { int compareto( T t ); 3

Comparable interface T implements Comparable<T> T t1, t2; 4

Comparable interface T implements Comparable<T> T t1, t2; Java API recommends that t1.compareto( t2 ) returns: 0, if t1.equals( t2 ) returns true positive number, if t1 > t2 negative number, if t1 < t2 5

Some classes assume comparable generic types. Their implementations call the compareto( ) method. e.g. PriorityQueue< E > (uses a heap with comparable E) TreeSet< E > (uses a balanced binary search tree with comparable E) TreeMap< K, V > (uses a balanced binary search tree with comparable K) 6

e.g. String implements Comparable<T> https://docs.oracle.com/javase/7/docs/api/java/lang/string.html 7

e.g. Character, Integer, Float, Double, BigInteger, etc all implement Comparable<T>. You cannot compare objects of these classes using the < operator. Instead use compareto( ).

Example: Circle Q: How can we define a compareto( Circle ) and equals( ) method for ordering Circle objects? A: Compare their radii or their areas. Java recommends overriding equals(object), rather than overloading. 9

public class Circle implements Comparable<Circle>{ private radius; public Circle(double radius){ // constructor this.radius = radius; public boolean equals(circle c) { return radius == c.getradius(); public int compareto(circle c) { return radius - c.getradius(); 10

Example: Rectangle Q: When are two Rectangle objects equal? A: Their heights are equal and their widths are equal. These are not equal: Q: How can we define a compareto() and equals( ) method for ordering Rectangle objects? 11

class Rectangle implements Comparable<Rectangle> Rectangle t1, t2; Java API recommends that t1.compareto( t2 ) returns: 0, if t1.equals( t2 ) returns true positive number, if t1 > t2 negative number, if t1 < t2 12

class Rectangle implements Comparable<Rectangle>{ // constructor. // getarea method boolean equals( Rectangle other ) { return (this.height == other.height) && (this.width == other.width); int compareto( Rectangle r ){ return this.getarea() - other.getarea(); This is not consistent with Java API recommendation on the previous slide. Why not? 13

class Rectangle implements Comparable<Rectangle>{ // constructor. // getarea method boolean equals( Rectangle other ) { return this.getarea() == other.getarea(); int compareto( Rectangle r ){ return this.getarea() - other.getarea(); This is consistent with Java API recommendation. But it is maybe not such a natural way to order rectangles. 14

COMP 250 Lecture 32 interfaces (Comparable, Iterable & Iterator) Nov. 22/23, 2017 15

Java Iterator interface Motivation 1: we often want to visit all the objects in some collection. e.g. linked list, binary search tree, hash map entries, vertices in a graph 16

Java Iterator interface Motivation 2: iterators. We sometimes want to have multiple Analogy: Multiple TA s grading a collection of exams. 17

Java Iterator interface interface Iterator<T> { boolean hasnext(); T next(); // returns current, and // advances to next void remove(); // optional; ignore it next() is a method, not a field like in the linked list class. 18

Recall lecture 5 and Exercises 3 class SLinkedList<E> { SNode<E> head; : private class SNode<E> { SNode<E> next; E element;. private class SLL_Iterator<E> implements Iterator<E>{.. 19

As we will see, the iterator object will reference a node in the list. head size 4 20

private class SLL_Iterator<E> implements Iterator<E>{ private SNode<E> cur; SLL_Iterator( SLinkedList<E> list){ // constructor cur = list.gethead(); public boolean hasnext() { return (cur!= null); public E next() { E element = cur.getelement; cur = cur.getnext(); return element; 21

Java Iterator interface Q: Who constructs the Iterator object for a collection class such as LinkedList, ArrayList, HashMap,? A: 22

Java Iterator interface Q: Who constructs the Iterator object for a collection class such as LinkedList, ArrayList, HashMap,? A: The class itself does it. How? A collection class is iterable if the class is able to make an iterator object that iterates over the elements. 23

Java Iterable interface interface Iterable<T> { Iterator<T> iterator(); It could have been called makeiterator(). If a class implements Iterable, then the class has an iterator() method, which constructs an Iterator object. 24

class SLinkedList<E> implements Iterable<E> { SNode<E> head; private class SNode<E> { SNode<E> next; E element;. private class SLL_Iterator<E> implements Iterator<E>{.. SLL_Iterator<E> iterator() { return new SLL_Iterator( this ); ; 25

private class SLL_Iterator<E> implements Iterator<E>{ size 4 head private SNode<E> cur; SLL_Iterator( SLinkedList<E> cur = list.gethead(); public boolean hasnext() { return (cur!= null); list){ public E next() { E element = cur.getelement; cur = cur.getnext(); return element; 26

LinkedList<Shape> list; Shape s; 27

LinkedList<Shape> list; Shape s; : Iterator<Shape> iter1 = list.iterator(); Iterator<Shape> iter2 = list.iterator(); s 28

LinkedList<Shape> list; Shape s; : Iterator<Shape> iter1 = list.iterator(); Iterator<Shape> iter2 = list.iterator(); s = iter1.next() s The iterators iterate over LinkedList nodes, not Shapes. The next() method returns Shapes. 29

LinkedList<Shape> list; Shape s; : Iterator<Shape> iter1 = list.iterator(); Iterator<Shape> iter2 = list.iterator(); s = iter1.next() s s = iter2.next() s = iter1.next() s = iter2.next() s = iter2.next() The iterators iterate over LinkedList nodes, not Shapes. The next() method returns Shapes. 30

interface List : interface Iterable iterator() interface Iterator next() hasnext() implements implements class SLinkedList : SLLIterator : iterator() class SLLIterator SNode Boolean next() hasnext() SLLIterator might be an inner class of SLinkedList. The iterator() method calls the constructor of the SLLIterator class. 31

Assignment 4: MyHashTable You will implement a hashtable (or hashmap). You will use the SLinkedList class from Exercises 4 to implement a HashLinkedList class which you will use for the buckets. You will implement a HashIterator class for your hash table. 32

ASIDE: Java enhanced for loop It can be used for any class that implements Iterable. Example: LinkedList<String>... list = new LinkedList<String>(); for (String s : list) { System.out.println( s ); 33