Objecves - Computer Science Department : …sprenkle/cs209/pre_class/09-collections.pdfObjecves •...

32
9/28/16 1 Objec-ves Collec-ons Ø Maps Traversing Collec-ons Excep-on handling Sept 30, 2016 Sprenkle - CSCI209 1 Review: Collec-ons Framework Interfaces Ø Abstract data types that represent collec-ons Ø Collec-ons can be manipulated independently of implementa-on Implementa.ons Ø Concrete implementa-ons of collec-on interfaces Ø Reusable data structures Algorithms Ø Methods that perform useful computa-ons on collec-ons, e.g., searching and sor-ng Ø Reusable func-onality Ø Polymorphic: same method can be used on many different implementa-ons of collec-on interface Sept 30, 2016 Sprenkle - CSCI209 2

Transcript of Objecves - Computer Science Department : …sprenkle/cs209/pre_class/09-collections.pdfObjecves •...

9/28/16

1

Objec-ves• Collec-ons

Ø Maps

• TraversingCollec-ons• Excep-onhandling

Sept30,2016 Sprenkle-CSCI209 1

Review:Collec-onsFramework• Interfaces

Ø Abstractdatatypesthatrepresentcollec-onsØ Collec-onscanbemanipulatedindependentlyofimplementa-on

• Implementa.onsØ Concreteimplementa-onsofcollec-oninterfacesØ Reusabledatastructures

• AlgorithmsØ Methodsthatperformusefulcomputa-onsoncollec-ons,e.g.,searchingandsor-ng

Ø Reusablefunc-onalityØ Polymorphic:samemethodcanbeusedonmanydifferentimplementa-onsofcollec-oninterface

Sept30,2016 Sprenkle-CSCI209 2

9/28/16

2

Review:CoreCollec-onInterfaces• Encapsulatedifferenttypesofcollec-ons

Sept30,2016 Sprenkle-CSCI209 3

MAPS

Sept30,2016 Sprenkle-CSCI209 4

9/28/16

3

Maps• Mapskeys(oftype<K>)tovalues(oftype<V>)

• NoduplicatekeysØ Eachkeymapstoatmostonevalue

Sept30,2016 Sprenkle-CSCI209 5

Map Interface• <V> put(<K> key, <V> value)Ø Returns old value that key mapped to

• <V> get(Object key) Ø Returns value at that key (or null if no

mapping)

• Set<K> keySet() Ø Returns the set of keys

Sept30,2016 Sprenkle-CSCI209 6

And more …

9/28/16

4

A few Map Implementa-ons• HashMap

Ø Fast

• TreeMapØ Sor-ngØ Key-ordereditera-on

• LinkedHashMapØ FastØ Inser-on-orderitera-on

Sept30,2016 Sprenkle-CSCI209 7

DeclaringMaps• Declaretypesforbothkeysandvalues• class HashMap<K,V>

Sept30,2016 Sprenkle-CSCI209 8

Keys are StringsValues are Lists of Strings

Map<String, List<String>> map = new HashMap<>();

Keys are StringsValues are Integers

Map<String, Integer> map = new HashMap<>();

9/28/16

5

ALGORITHMS

Sept30,2016 Sprenkle-CSCI209 9

Collec-onsFramework’sAlgorithms• Polymorphicalgorithms• Reusablefunc-onality• ImplementedintheCollections class

Ø Sta-cmethods,1stargumentisthecollec-on

Ø SimilartoArraysclass,whichoperatesonarrays

Sept30,2016 Sprenkle-CSCI209 10

9/28/16

6

OverviewofAvailableAlgorithms• Sor-ng–op-onalComparator• Shuffling• Searching–binarySearch• Rou-nedatamanipula-on:reverse*,copy*,fill*,swap*,addAll

• Composi-on–frequency,disjoint• Findingmin,max

Sept30,2016 Sprenkle-CSCI209 11

* Only Lists

TRAVERSINGCOLLECTIONS

Sept30,2016 Sprenkle-CSCI209 12

9/28/16

7

TwoWaystoIterateoverCollec-ons• For-eachloop• Iterator

Sept30,2016 Sprenkle-CSCI209 13

TraversingCollec-ons:For-eachLoop• For-eachloop:

• ValidforallCollectionsØ Maps (anditsimplementa-ons)arenotCollections• But,Map’skeySet()isaSet andvalues()isaCollection

Sept30,2016 Sprenkle-CSCI209 14

for (Object o : collection) System.out.println(o);

Or whatever data type is appropriate

9/28/16

8

TraversingCollec-ons:Iterator• Iterator: JavaInterface• TogetanIterator fromaCollection object:

Ø ReturnsanIterator overtheelementsinthiscollec-on

Ø Example:

Sept30,2016 Sprenkle-CSCI209 15

Iterator<E> iterator()

Iterator<String> iter = keys.iterator();

Sept30,2016 Sprenkle-CSCI209 16

Iterator:LikeaCursor• Alwaysbetweentwoelements

Iterator<Integer> i = list.iterator();while( i.hasNext()) {

int value = i.next();…

}

9/28/16

9

Iterator API • <E> next()

Ø Getthenextelement

•  boolean hasNext() Ø Aretheremoreelements?

•  void remove() Ø RemovethepreviouselementØ Onlysafewaytoremoveelementsduringitera-on

• Notknownwhatwillhappenifremoveelementsinfor-eachloop

Sept30,2016 Sprenkle-CSCI209 17

Sept30,2016 Sprenkle-CSCI209 18

PolymorphicFilterAlgorithm

static void filter(Collection c) { Iterator i = c.iterator();

while( i.hasNext() ) {// if the next element does not// adhere to the condition, remove it if ( ! condition(i.next()) ) {

i.remove();}

}}

Polymorphic: works regardless of Collection implementation

9/28/16

10

Sept30,2016 Sprenkle-CSCI209 19

TraversingLists:ListIterator• Methodstotraverselistbackwardstoo

Ø hasPrevious()Ø previous()

• To get a ListIterator: Ø listIterator(int position)

• Passinsize()asposi-ontogetatendoflist

Key difference

Sept30,2016 Sprenkle-CSCI209 20

Enumeration• Legacyclass• SimilartoIterator• Example methods:

Ø boolean hasMoreElements() Ø Object nextElement()

• Longermethodnames• Doesn’thaveremoveopera-on

9/28/16

11

HowNottoIterate• Don’tusegettoaccessList

Ø Ifimplementa-onisaLinkedList,performanceisreeeeeallyslow

Sept30,2016 Sprenkle-CSCI209 21

for (int i = 0; i < list.size(); i++) {count += list.get(i); // do something

}

Sept30,2016 Sprenkle-CSCI209 22

SynchronizedCollec-onClasses• Formul-plethreadssharingsamecollec-on• Slowdowntypicalprograms

Ø Avoidfornow• e.g.,Vector, Hashtable• Seejava.util.concurrent

Another example: StringBuffer is synchronized, �whereas StringBuilder is not

9/28/16

12

BenefitsofCollec-onsFramework• ??

Sept30,2016 Sprenkle-CSCI209 23

EXCEPTIONS

Sept30,2016 Sprenkle-CSCI209 24

9/28/16

13

Sept30,2016 Sprenkle-CSCI209 25

Errors• Programsencountererrorswhentheyrun

Ø UsersmayenterdatainthewrongformØ FilesmaynotexistØ Programcodehasbugs!*

• Whenanerroroccurs,aprogramshoulddooneoftwothings:Ø Reverttoastablestateandcon-nueØ Allowtheusertosavedataandthenexittheprogramgracefully

* (Of course, not your programs)

Sept30,2016 Sprenkle-CSCI209 26

JavaMethodBehavior• Normal/correctcase:returnspecifiedreturntype• Errorcase:doesnotreturnanything,throws anExceptionØ Anexcep-onisaneventthatoccursduringexecu-onofaprogramthatdisruptsnormalflowofprogram'sinstruc-ons

Ø Exception: objectthatencapsulateserrorinforma-on

Similar to Python

9/28/16

14

Sept30,2016 Sprenkle-CSCI209 27

HandlingExcep-ons• JVM’sexcep.on-handlingmechanismsearchesforanexcep.onhandler—theerrorrecoverycodeØ  Excep-onhandlerdealswithapar3cularexcep-onØ  Searchescallstackforamethodthatcanhandle(orcatch)the

excep-on

1

2

3

4

Callstack

Search order for handler

Sept30,2016 Sprenkle-CSCI209 28

Throwable• Allexcep-onsindirectlyderivefromThrowable

Ø Childclasses:ErrorandException• ImportantThrowable methods

Ø getMessage()• Detailedmessageabouterror

Ø printStackTrace()• Printsoutwhereproblemoccurredandpathtoreachthatpoint

Ø getStackTrace()• Getthestackinnon-textformat

Error

Throwable

Exception

9/28/16

15

Sept30,2016 Sprenkle-CSCI209 29

Prin-ngStackTraceExample

How helpful is this output?How user friendly is it?

java.io.FileNotFoundException: fred.txtat java.io.FileInputStream.<init>(FileInputStream.java)at java.io.FileInputStream.<init>(FileInputStream.java)at ExTest.readMyFile(ExTest.java:19)at ExTest.main(ExTest.java:7)

Sept30,2016 Sprenkle-CSCI209 30

Excep-onClassifica-on:Error• Aninternalerror• Strongconven-on:reservedforJVM

Ø JVM-generatedwhenresourceexhaus-onoraninternalproblem• Example:OutofMemoryerror

• Program’scodeshouldnotandcannotthrowanobjectofthistype

• Uncheckedexcep-on

When can that happen in Java?

9/28/16

16

Sept30,2016 Sprenkle-CSCI209 31

Excep-onClassifica-on:Exception1.  RuntimeException:somethingthat

happensbecauseofaprogrammingerrorØ Uncheckedexcep-onØ Examples:ArrayOutOfBoundsException, NullPointerException, ClassCastException

2.   Checkedexcep-onsØ Awell-wrirenapplica-onshouldan-cipateandrecoverfrom• Compilerenforces

Ø Examples:IOException, SQLException

Error

Sept30,2016 Sprenkle-CSCI209 32

Excep-onClassifica-onThrowable

Exception

IOExceptionRuntimeException

SQLException

Others…

UncheckedChecked

Checked

Checked: All non- RuntimeExceptions

Partofjava.lang package

9/28/16

17

TypesofExcep-onsUnchecked• Anyexcep-onthatderivesfromError orRuntimeException

•  Programmerdoesnotcreate/handle

•  Trytomakesurethattheydon’toccur

• OsenindicatesprogrammererrorØ  E.g.,precondi-onviola-ons,

notusingAPIcorrectly

Checked• Anyotherexcep-on•  Programmercreatesandhandlescheckedexcep-ons

• Compiler-enforcedcheckingØ  Improvesreliability*

•  Forcondi-onsfromwhichcallercanreasonablybeexpectedtorecover

Sept30,2016 Sprenkle-CSCI209 33

TypesofUncheckedExcep-ons1.  DerivedfromtheclassError

Ø Anylineofcodecangeneratebecauseitisaninternalerror

Ø Don’tworryaboutwhattodoifthishappens2.  DerivedfromtheclassRuntimeException

Ø IndicatesabugintheprogramØ FixthebugØ Examples:ArrayOutOfBoundsException, NullPointerException, ClassCastException

Sept30,2016 Sprenkle-CSCI209 34

9/28/16

18

CheckedExcep-ons• Needtobehandledbyyourprogram

Ø Compiler-enforcedØ Improvesreliability*

• Foreachmethod,tellthecompiler:Ø WhatthemethodreturnsØ Whatcouldpossiblygowrong

• Adver3setheexcep-onsthatamethodthrows• Helpsusersofyourinterfaceknowwhatmethoddoesandletsthemdecidehowtohandleexcep-ons

Sept30,2016 Sprenkle-CSCI209 35

THROWINGEXCEPTIONS

Sept30,2016 Sprenkle-CSCI209 36

9/28/16

19

MethodsandExcep-onsExample• BufferedReader hasmethodreadLine()

Ø Readsalinefromastream,suchasafileornetworkconnec-on

• Methodheader:

• Interpre-ngtheheader:readLine willØ returnaString(ifeverythingwentright)Ø throwanIOException(ifsomethingwentwrong)

Sept30,2016 Sprenkle-CSCI209 37

public String readLine() throws IOException

PartofAdver-sing

Adver-singCheckedExcep-ons• Adver-sing:inJavadoc,documentunderwhatcondi-onseachexcep-onisthrownØ @throws tag

• Examplesofwhenyourmethodshouldadver-sethecheckedexcep-onsthatitmaythrowØ Yourmethodcallsamethodthatthrowsacheckedexcep-on

Ø Yourmethoddetectsanerrorinitsprocessinganddecidestothrowanexcep-on

Sept30,2016 Sprenkle-CSCI209 38

9/28/16

20

Sept30,2016 Sprenkle-CSCI209 39

Example:PassinganExcep-on“Up”

• readData()callsreadLine(),whichcanthrowanIOException

• If readLine()throwsthisexcep-ontoourmethodØ readData() throwstheexcep-onaswellØ WhoevercallsreadDatawillhandleexcep-on

public String readData(BufferedReader in) throws IOException {

String str1 = in.readLine();return str1;

} Throws an IOException

Sept30,2016 Sprenkle-CSCI209 40

ThrowingAnExcep-onWeCreated

1.  CreateanewobjectofclassIllegalArgumentExceptionØ ClassderivedfromRuntimeException

2. throw itØ MethodendsatthispointØ Callingmethodhandlesexcep-on

if (grade < 0 || grade > 100) {throw new IllegalArgumentException();

}

Equivalent in Python?

9/28/16

21

Sept30,2016 Sprenkle-CSCI209 41

AMoreDescrip-veExcep-on• FourconstructorsformostExcep-onclasses

Ø Default(noparameters)Ø TakesaString message

• Describethecondi-onthatgeneratedthisexcep-onmorefully

Ø 2more

Best messages include all state that could have contributed to the problem

if (grade < 0 || grade > 100) {throw new IllegalArgumentException(

"Grade is not in valid range (0-100)");}

CommonExcep-onsName PurposeIllegalArgumentException Whencallerpassesininappropriate

argumentIllegalStateException Invoca-onisillegalbecauseofreceiving

object’sstate.(Ex:closingaclosedwindow)

• BothinheritfromRuntimeException• Mayseemlikethesecovereverythingbutonlyusedforcertainkindsofillegalargumentsandexcep-ons

• NotusedwhenØ  Anullargumentpassedin;shouldbeaNullPointerException

Ø  Passininvalidindexforanarray;shouldbeanIndexOutOfBoundsException

Sept30,2016 Sprenkle-CSCI209 42

9/28/16

22

Goal:FailureAtomicity• Aseranobjectthrowsanexcep-on,theobjectshouldbeinawell-defined,usablestateØ Afailedmethodinvoca-onshouldleaveobjectinstatepriortoinvoca-on

• Approaches:Ø Checkparameters/statebeforeperformingopera-on(s)Ø Dothefailure-proneopera-onsfirstØ Userecoverycodeto“rollback”stateØ Applytotemporaryobjectfirst,thencopyovervalues

Sept30,2016 Sprenkle-CSCI209 43

CATCHINGEXCEPTIONS

Sept30,2016 Sprenkle-CSCI209 44

9/28/16

23

Error

Sept30,2016 Sprenkle-CSCI209 45

Excep-onClassifica-onThrowable

Exception

IOExceptionRuntimeException

SQLException

Others…

UncheckedChecked

Checked

Checked: All non- RuntimeExceptions

Partofjava.lang package

Sept30,2016 Sprenkle-CSCI209 46

CatchingExcep-ons• Aserwethrowanexcep-on,somepartofprogramneedstocatchitØ Knowshowtodealwiththesitua-onthatcausedtheexcep-on

Ø Handlestheproblem—hopefullygracefully,withoutexi-ng

9/28/16

24

Sept30,2016 Sprenkle-CSCI209 47

Try/CatchBlock

• Thesimplestwaytocatchanexcep-on• Syntax:

try {code;more code;

} catch (ExceptionType e) {

error code for ExceptionType;}catch (ExceptionType2 e) {

error code for ExceptionType2;}…

Python equivalent?

Sept30,2016 Sprenkle-CSCI209 48

Try/CatchBlock

• Codeintryblockrunsfirst• Iftryblockcompleteswithoutanexcep-on,catchblock(s)arenotexecuted

• Iftrycodegeneratesanexcep-onØ AcatchblockrunsØ Remainingcodeintryblockisnotexecuted

• Ifanexcep-onofatypeotherthanExceptionType isthrowninsidetryblock,methodexitsimmediately*

try {code;more code;

} catch (ExceptionType e) {

error code forExceptionType

}

9/28/16

25

Sept30,2016 Sprenkle-CSCI209 49

Try/CatchBlock

• YoucanhavemorethanonecatchblockØ Tohandle>1typeofexcep-on

• Ifexcep-onisnotoftypeExceptionType1,fallstoExceptionType2,andsoforthØ Runthefirstmatchingcatchblock

try {code;more code;

} catch (ExceptionType e) {

error code forExceptionType

}catch (ExceptionType2 e) {

error code for ExceptionType2

}

Can catch any exception with Exception e but won’t have customized messages

Sept30,2016 Sprenkle-CSCI209 50

Try/CatchExamplepublic void read(BufferedReader in) {

try {boolean done = false;while (!done) {

String line=in.readLine();// above could throw IOException!if (line == null)

done = true;}

} catch (IOException ex) {

ex.printStackTrace();}

}Prints out stack trace to method call

that caused the error

9/28/16

26

Sept30,2016 Sprenkle-CSCI209 51

Try/CatchExamplepublic void read(BufferedReader in) {

try {boolean done = false;while (!done) {

String line=in.readLine();// above could throw IOException!if (line == null)

done = true;}

} catch (IOException ex) {

ex.printStackTrace();}

}More precise catch may help pinpoint error

But could result in messier code

Sept30,2016 Sprenkle-CSCI209 52

Thefinally Block

• Allowsyoutocleanupordomaintenancebeforemethodends(onewayortheother)Ø E.g.,closingfilesordatabaseconnec-ons

try {…

} catch (Exception e) {

…}finally {

…}

• Op-onal:addafinallyblockaserallcatchblocksØ Codeinfinally blockalwaysrunsasercodeintry and/orcatchblocks• Asertry blockfinishesor,ifanexcep-onoccurs,aserthecatchblockfinishes

FinallyTest.java

9/28/16

27

WhattodowithaCaughtExcep-on?• Dumpthestackasertheexcep-onoccurs

Ø Whatelsecanwedo?

• Generally,twoop-ons:1.  Catchtheexcep-onandrecoverfromit2.  Passexcep-onuptowhoevercalledit

Sept30,2016 Sprenkle-CSCI209 53

ToThroworCatch?• Problem:lower-levelexcep-onpropagateduptohigher-levelcode

• Example:userentersaccountinforma-onandgetsexcep-onmessage“fieldexceedsallowedlengthindatabase”Ø LostcontextØ Lower-leveldetailpollu-nghigher-levelAPI

Sept30,2016 Sprenkle-CSCI209 54

Solution: higher-levels should catch lower-level exceptions �and throw them in terms of higher-level abstraction

GUI

DB

Excep-onhere

Handled here

9/28/16

28

Excep-onTransla-on

• Specialcase:Excep-onChainingØ Whenhigher-levelexcep-onneedsinfofromlower-levelexcep-on

Sept30,2016 Sprenkle-CSCI209 55

try {// Call lower-level abstraction

}catch (LowerLevelException ex) {

// log exception …throw new HigherLevelException(…);

}

try {// Call lower-level abstraction

}catch (LowerLevelException cause) {

// log exception …throw new HigherLevelException(cause);

}

Most standard Exceptions have this

constructor

GuidelinesforExcep-onTransla-on• Trytoensurethatlower-levelAPIssucceed

Ø Ex:verifythatyourparameterssa-sfyinvariants

• Insulatehigher-levelfromlower-levelexcep-onsØ HandleinsomereasonablewayØ Alwayslogproblemsoadmincancheck

• Ifcan’tdoprevioustwo,thenuseexcep-ontransla-on

Sept30,2016 Sprenkle-CSCI209 56

9/28/16

29

Summary:MethodsThrowingExcep-ons• APIdocumenta-ontellsyouifamethodcanthrowanexcep-onØ Ifso,youmusthandleit

• Ifyourmethodcouldpossiblythrowanexcep-on(bygenera-ngitorbycallinganothermethodthatcould),adver-seit!Ø Ifyoucan’thandleeveryerror,that’sOK…letwhoeveriscallingyouworryaboutit

Ø However,theycanonlyhandletheerrorifyouadver-setheexcep-onsyoucan’tdealwith

Sept30,2016 Sprenkle-CSCI209 57

ProgrammingwithExcep-ons• Excep-onhandlingisslow

• Useonebigtry blockinsteadofnes-ngtry-catch blocksØ SpeedsupExcep-onHandlingØ Otherwise,codegetstoomessy

• Don'tignoreexcep-ons(e.g.,catch blockdoesnothing)Ø Berertopassthemalongtohighercalls

Sept30,2016 Sprenkle-CSCI209 58

try {}catch () { }try {}catch () { }

try {try {}catch () { }

}catch () { }

try {……

}catch () { }

9/28/16

30

Crea-ngOurOwnExcep-onClass• Trytoreuseanexis-ngexcep-on

Ø Matchinnameaswellasseman-cs

• IfyoucannotfindapredefinedJavaExceptionclassthatdescribesyourcondi-on,implementanewExceptionclass!

Sept30,2016 Sprenkle-CSCI209 59

Sept30,2016 Sprenkle-CSCI209 60

Crea-ngOurOwnExcep-onClass

public class FileFormatException extends IOException {public FileFormatException() {

}

public FileFormatException(String message) {super(message);

}

// other 2 standard constructors…}

• Cannowthrowexcep-onsoftypeFileFormatException

What happens in this constructor implicitly?

Is this a checked or unchecked exception?

9/28/16

31

GuidelinesforCrea-ngYourOwnExcep-onClasses

• Includeaccessormethodstogetmoreinforma-onaboutthecauseoftheexcep-onØ “failure-captureinforma-on”

• Checkedoruncheckedexcep-on?Ø Checked:forcesAPIusertohandleBUTmoredifficulttouseAPI• Hastohandleallcheckedexcep-ons

Ø Usecheckedexcep-onifexcep-onalcondi-oncannotbepreventedbyproperuseofAPIandAPIusercantakeausefulac-onaserward

Sept30,2016 Sprenkle-CSCI209 61

Prac-ce:DesigningaNewExcep-onClass

• Scenario:Whenanarempttomakeapurchasewithagiscardfailsbecausecarddoesn’thaveenoughmoney,throwanewexcep-onthatyoucreated

• RecallthatallExceptionsareThrowable,sotheyhavethemethods:getMessage(), printStackTrace(), getStackTrace()

Sept30,2016 Sprenkle-CSCI209 62

• How would someone else use your class?• What constructors, additional method(s) may you want to add for your exception class?

9/28/16

32

Sept30,2016 Sprenkle-CSCI209 63

BenefitsofExcep-ons?

JavadocGuidelinesabout@throws• Alwaysreportifthrowcheckedexcep-ons• Reportanyuncheckedexcep-onsthatthecallermightreasonablywanttocatchØ Excep-on:NullPointerExceptionØ Allowscallertohandle(ornot)Ø Documentexcep-onsthatareindependentoftheunderlyingimplementa-on

• Errorsshouldnotbedocumentedastheyareunpredictable

Sept30,2016 Sprenkle-CSCI209 64