Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Similar documents
Topic 10: The Java Collections Framework (and Iterators)

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

MIT AITI Lecture 18 Collections - Part 1

Exceptions. CSC207 Winter 2017

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Programming II (CS300)

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

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

Programming II (CS300)

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

CS Programming Language Java. Fall 2004 Sept. 29

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

USAL1J: Java Collections. S. Rosmorduc

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

5/23/2015. Core Java Syllabus. VikRam ShaRma

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Collections, Maps and Generics

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS11 Java. Winter Lecture 8

Inheritance and Interfaces

Java: exceptions and genericity

Polymorphism. return a.doublevalue() + b.doublevalue();

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

CS61BL Summer 2013 Midterm 2

Exploring the Java API, Packages & Collections

Interview Questions I received in 2017 and 2018

CS159. Nathan Sprague

Core Java Contents. Duration: 25 Hours (1 Month)

Principles of Software Construction: Objects, Design and Concurrency. Exceptions, scope, static data and methods, and Generics.

Internal Classes and Exceptions

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

Interfaces, collections and comparisons

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

2.6 Error, exception and event handling

Programming Languages and Techniques (CIS120)

COMP1008 Exceptions. Runtime Error

Cloning Enums. Cloning and Enums BIU OOP

JAVA. Duration: 2 Months

Casting. References. References

Hash table basics. ate à. à à mod à 83

Java Bytecode (binary file)

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

Programming Language Concepts: Lecture 7

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

Highlights of Last Week

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

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Exception-Handling Overview

CMSC 132: Object-Oriented Programming II

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

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

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

Java Review: Objects

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

CS2110: Software Development Methods. Maps and Sets in Java

CS 251 Intermediate Programming Inheritance

CONTAİNERS COLLECTİONS

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Introduction to Computing II (ITI 1121) Final Examination

CS159. Nathan Sprague

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

TECHNICAL WHITEPAPER. Performance Evaluation Java Collections Framework. Performance Evaluation Java Collections. Technical Whitepaper.

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

COP 3330 Final Exam Review

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Object-Oriented Programming with Java

Programming Languages and Techniques (CIS120)

Sets and Maps. Part of the Collections Framework

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

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Tony Valderrama, SIPB IAP 2010

Building Java Programs

INTRODUCTION TO DATA AND PROCEDURE

Java Collections Framework. 24 April 2013 OSU CSE 1

The class Object. Lecture CS1122 Summer 2008

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

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

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

Java Collections Framework reloaded

Object-Oriented Programming

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

Generic classes & the Java Collections Framework. *Really* Reusable Code

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

What is the Java Collections Framework?

CSC 1214: Object-Oriented Programming

Regular Expressions ("reguläre Ausdrücke", "regexp")

Programming Language Concepts: Lecture 7

Java Map and Set collections

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

Lecture 16: Case Study: The Java Collections API

Transcription:

Today Book-keeping Exceptions Subscribe to sipb-iap-java-students Collections http://sipb.mit.edu/iap/java/ Play with problem set 1 No class Monday (MLK); happy Hunting Problem set 2 on Tuesday 1 2 So far... Handling errors OOP, inheritance What if there s an error? Abstract classes Interfaces Example: list of Objects, want to find one and return its index What if not in list? Traditional C response: values (like -1) return special Need the programmer to remember to notice and special-case it 3 4

Exceptions What is an Exception? Java response: throw an exception Exception is a standard Java class Abnormal return from function throw keyword exits out of current code Calling code needs to catch it Nearest enclosing and matching catch block (possibly in a calling function) gets the exception, or else the program ends 5 6 Throwing exceptions import java.util.nosuchelementexception; // Inside some class private int finditem(int n, int[] arr) throws NoSuchElementException { for (int i = 0; i < arr.length; i++) { if (arr[i] == n) return i; throw new NoSuchElementException(); Catching exceptions try { int offset = obj.finditem(17); // use offset somehow catch (NoSuchElementException e) { // handle appropriately 7 8

Exceptions syntax Catching throw obj: throws an Exception object Can have multiple catch blocks try {... catch (ExceptionType name) {... First catch block with matching exception class (or a superclass) is invoked Executes the try block until an exception occurs, then jumps to matching catch code finally block, if present, does clean-up after try code 9 10 Catching, cont d Runtime exceptions try { // some code if (something) throw new NoSuchElementException(); catch (ClassCastException e) { // We don t end up here catch (Exception e) { // We get caught here finally { // Do cleanup Checked (normal) exceptions must either be caught or declared with throws Unchecked exceptions must be derived from RuntimeException; don t have to be declared Implicitly passed to caller if not caught 11 12

Exception class boilerplate Digression public class MyException extends Exception { public MyException() { super(); public MyException(String s) { super(s); Data types influence your algorithms..and vice versa! 13 14 Container classes Generalities Often want to store variable amounts of data Can t use int[] arrays; constant size Don t want to keep writing linked lists Classes in java.util All subclasses of Collection interface All store Objects; need to cast to correct type when retrieving Java APIs to the rescue Various performance trade-offs No special requirements (mostly; working hashcode sometimes) http://java.sun.com/j2se/1.4.2/docs/guide/col Optimized for various situations 15 16

Generic collections Iterator Collection c; c.add(o); c.clear(); // Comes from somewhere // any Object // empties c Allows each element to collection to be accessed in turn if (c.isempty()) //... Common way to loop over contents using a while loop int numelems = c.size(); Collection c2; c = new ArrayList(c2); // Does a shallow copy Can t modify collection while iterating except via iterator 17 18 Iterators, an example Collections to arrays Iterator iter = c.iterator(); Object o = iter.next(); // Can t say: // Rect r = iter.next(); Collection.toArray() returns a generic Object[] Need to make sure the array is of the right run-time type Solution: create the correct type of array beforehand, use casting 19 20

Collections to arrays, an example Fast vs. Slow Collection c; // set and filled from somewhere MyObject[] array = new MyObject[1]; array = (MyObject[])c.toArray(array); Algorithmic complexity O(n): operation takes time proportional to size of set; searching for item in unsorted list O(1): operation takes constant time; searching for item in hash table 21 22 Lists List is an interface; multiple implementations Ordered Can contain duplicates Default add is to end of list Lists, an example List l; // comes from somewhere; couple of options l.add(new Integer(4)); // can t add an int l.add(new Integer(8)); l.add(new Integer(6)); Iterator iter = l.iterator(); Integer i = (Integer)iter.next(); System.out.println(i); // Prints 4 8 6 23 24

List options LinkedList: fast insertion, iteration ArrayList: fast indexed access Vector: deprecated, mostly List operations List l = new ArrayList(); Object o; // from somewhere // Insert at arbitrary point: l.add(o,2); // Return arbitrary element: // (slow in LinkedList) o = l.get(1); // Find index of an object (slow, uses.equals) int i = l.indexof(o); // Replace an element: l.set(0, o); 25 26 Sets Set options Mathematical set HashSet: generally fast No guarantees on ordering No duplicates (according to.equals()) TreeSet: somewhat slower, but stores in sorted order. Objects inserted must implement Comparable interface Can t store mutable objects (.hashcode() can t change) contains() is fast No special operations 27 28

Comparable objects Comparable is an interface implementors provide compareto method Returns positive if this > o Returns negative if this < o Returns 0 if this.equals(o) Using sets: HashSet Set s = new HashSet(); s.add(new Integer(3)); s.add(new Integer(2)); s.add(new Integer(3)); // has no effect System.out.println(s.size()); // is 2 Iterator iter = s.iterator(); Integer i = (Integer)iter.next(); System.out.println(i); // May print 2, 3 or 3, 2 29 30 Using sets: TreeSet Maps Set s = new TreeSet(); s.add(new Integer(3)); s.add(new Integer(2)); s.add(new Integer(3)); // has no effect System.out.println(s.size()); // is 2 Iterator iter = s.iterator(); Integer i = (Integer)iter.next(); System.out.println(i); // Always prints 2, 3 Associates value with a key Keys act like a Set HashMap and TreeMap classes 31 32

Using maps In summary Maps ages = new HashMap(); ages.put("alex", new Integer(17)); ages.put("mark", new Integer(22)); // Keys don t have to be Strings Iterators Collections: lists, sets, hashes if (ages.containskey("alex")) { //... Iterator iter = ages.keyset().iterator(); String name = (String)iter.next(); Integer age = (Integer)ages.get(name); System.out.println(name + ": " + age); // Could print in any order 33 34 Tuesday File I/O Tools for debugging Inner classes 35