objecves - computer science department : …sprenkle/cs209/in_class/09-inclass.pdfobjecves •...
TRANSCRIPT
9/30/16
1
Objec-ves• Collec-ons
Ø Maps
• Traversing• Excep-ons
Sept30,2016 Sprenkle-CSCI209 1
“Rather than teach everyone to code, �let's teach them to think. �The coding can come later; it's easier.” � - @rob_pike
On my Twitter feed:
Analysisofequals methods
Sept30,2016 Sprenkle-CSCI209 2
public boolean equals(Object o){if(((Birthday) o).getDay() != this.getDay())
return false;
if( ((Birthday) o).getMonth() != this.getMonth())return false;
return true;}
public boolean equals(Object o) {Birthday other = (Birthday) o;
if (this.month == other.month && this.day == other.day)
return true;else
return false;}
9/30/16
2
Usingbooleansinifstatements
Sept30,2016 Sprenkle-CSCI209 3
if( this.equals(that) == true ) {System.out.println("equal!");
}
if( this.equals(that) ) {System.out.println("equal!");
}
Review• Whatarethe3componentsoftheJavaCollec-onFramework?
• Whatdatatypescancollec-onshold?• Howcanweconvertaprimi-vetypeintoitsrespec-veWrapperObjecttype?
• Whatisthesyntaxtosaywhattypethecollec-onholds?
• WhydidIwaitun-lnowtoshowyouEclipse?
Sept30,2016 Sprenkle-CSCI209 4
9/30/16
3
Eclipse• Veryhelpful–a"eryouknowwhatyou’redoing
Ø Givessugges-onsforfixes• Youneedtothinkthroughwhattheappropriatefixis
Sept30,2016 Sprenkle-CSCI209 5
EclipseHints• A\eryouhavewri]enamethod,type
beforethemethod,andthenhitenterandtheJavadocstemplatewillbeautoma-callygeneratedforyou
• Usecommand-spacebarforpossiblecomple-ons
Sept30,2016 Sprenkle-CSCI209 6
/**
9/30/16
4
EclipseDiscussion• Helpfulhints
Ø Control-spacebarØ FormatthefileØ Auto-templatesforJavadocs
Sept30,2016 Sprenkle-CSCI209 7
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 8
9/30/16
5
Review:CoreCollec-onInterfaces• Encapsulatedifferenttypesofcollec-ons
Sept30,2016 Sprenkle-CSCI209 9
MAPS
Sept30,2016 Sprenkle-CSCI209 10
9/30/16
6
Maps• Mapskeys(oftype<K>)tovalues(oftype<V>)
• NoduplicatekeysØ Eachkeymapstoatmostonevalue
Sept30,2016 Sprenkle-CSCI209 11
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 12
And more …
9/30/16
7
A few Map Implementa-ons• HashMap
Ø Fast
• TreeMapØ Sor-ngØ Key-ordereditera-on
• LinkedHashMapØ FastØ Inser-on-orderitera-on
Sept30,2016 Sprenkle-CSCI209 13
DeclaringMaps• Declaretypesforbothkeysandvalues• class HashMap<K,V>
Sept30,2016 Sprenkle-CSCI209 14
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/30/16
8
ALGORITHMS
Sept30,2016 Sprenkle-CSCI209 15
Collec-onsFramework’sAlgorithms• Polymorphicalgorithms• Reusablefunc-onality• ImplementedintheCollections class
Ø Sta-cmethods,1stargumentisthecollec-on
Ø SimilartoArraysclass,whichoperatesonarrays
Sept30,2016 Sprenkle-CSCI209 16
9/30/16
9
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 17
* Only Lists
TRAVERSINGCOLLECTIONS
Sept30,2016 Sprenkle-CSCI209 18
9/30/16
10
TraversingCollec-ons:For-eachLoop• For-eachloop:
• ValidforallCollectionsØ Maps (anditsimplementa-ons)arenotCollections• But,Map’skeySet()isaSet andvalues()isaCollection
Sept30,2016 Sprenkle-CSCI209 19
for (Object o : collection) System.out.println(o);
Or whatever data type is appropriate
Sept30,2016 Sprenkle-CSCI209 20
Iterator:LikeaCursor• Alwaysbetweentwoelements
Iterator<Integer> i = list.iterator();while( i.hasNext()) {
int value = i.next();…
}
9/30/16
11
Iterator API • <E> next()
Ø Getthenextelement
• boolean hasNext() Ø Aretheremoreelements?
• void remove() Ø RemovethepreviouselementØ Onlysafewaytoremoveelementsduringitera-on
• Notknownwhatwillhappenifremoveelementsinfor-eachloop
Sept30,2016 Sprenkle-CSCI209 21
Sept30,2016 Sprenkle-CSCI209 22
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/30/16
12
Sept30,2016 Sprenkle-CSCI209 23
TraversingLists:ListIterator• Methodstotraverselistbackwardstoo
Ø hasPrevious()Ø previous()
• To get a ListIterator: Ø listIterator(int position)
• Passinsize()asposi-ontogetatendoflist
Key difference
HowNottoIterate• Don’tusegettoaccessList
Ø Ifimplementa-onisaLinkedList,performanceisreeeeeallyslow
Sept30,2016 Sprenkle-CSCI209 24
for (int i = 0; i < list.size(); i++) {count += list.get(i); // do something
}
9/30/16
13
BenefitsofCollec-onsFramework• ?
Sept30,2016 Sprenkle-CSCI209 25
BenefitsofCollec-onsFramework• Providescommon,well-knowninterface
Ø AllowsinteroperabilityamongunrelatedAPIsØ ReducesefforttolearnandtousenewAPIsfordifferent
implementa-ons• Reducesprogrammingeffort:providesuseful,reusabledatastructuresandalgorithms
• Increasesprogramspeedandquality:provideshigh-performance,high-qualityimplementa-onsofdatastructuresandalgorithms;interchangeableimplementa-onsàtuning
• ReducesefforttodesignnewAPIs:usestandardcollec-oninterfaceforyourcollec-on
• FosterssoMwarereuse:Newdatastructures/algorithmsthatconformtothestandardcollec-oninterfacesarereusable
Sept30,2016 Sprenkle-CSCI209 26
9/30/16
14
EXCEPTIONS
Sept30,2016 Sprenkle-CSCI209 27
Sept30,2016 Sprenkle-CSCI209 28
Errors• Programsencountererrorswhentheyrun
Ø UsersmayenterdatainthewrongformØ FilesmaynotexistØ Programcodehasbugs!*
• Whenanerroroccurs,aprogramshoulddooneoftwothings:Ø Reverttoastablestateandcon-nueØ Allowtheusertosavedataandthenexittheprogramgracefully
* (Of course, not your programs)
9/30/16
15
Sept30,2016 Sprenkle-CSCI209 29
JavaMethodBehavior• Normal/correctcase:returnspecifiedreturntype• Errorcase:doesnotreturnanything,throws anExceptionØ Anexcep-onisaneventthatoccursduringexecu-onofaprogramthatdisruptsnormalflowofprogram'sinstruc-ons
Ø Exception: objectthatencapsulateserrorinforma-on
Similar to Python
Sept30,2016 Sprenkle-CSCI209 30
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)
9/30/16
16
Prin-ngStackTraceExample
• Usefulfordebuggingyourcode• Generate/displayuser-friendlyerrorsinfinishedproduct
• O\enrequires“higher-levelcode”tohandleexcep-on
Sept30,2016 Sprenkle-CSCI209 31
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)
How helpful is this output?How user friendly is it?
Sept30,2016 Sprenkle-CSCI209 32
Excep-onClassifica-on:Error• Aninternalerror• Strongconven-on:reservedforJVM
Ø JVM-generatedwhenresourceexhaus-onoraninternalproblem• Example:OutofMemoryerror
• Program’scodeshouldnotandcannotthrowanobjectofthistype
• Uncheckedexcep-on
When can that happen in Java?
9/30/16
17
Sept30,2016 Sprenkle-CSCI209 33
Excep-onClassifica-on:Exception1. RuntimeException:somethingthat
happensbecauseofaprogrammingerrorØ Uncheckedexcep-onØ Examples:ArrayOutOfBoundsException, NullPointerException, ClassCastException
2. Checkedexcep-onsØ Awell-wri]enapplica-onshouldan-cipateandrecoverfrom• Compilerenforces
Ø Examples:IOException, SQLException
Error
Sept30,2016 Sprenkle-CSCI209 34
Excep-onClassifica-onThrowable
Exception
IOExceptionRuntimeException
SQLException
Others…
UncheckedCh
ecked
Checked
Checked: All non- RuntimeExceptions
Partofjava.lang package
9/30/16
18
TypesofExcep-onsUnchecked• Anyexcep-onthatderivesfromError orRuntimeException
• Programmerdoesnotcreate/handle
• Trytomakesurethattheydon’toccur
• O\enindicatesprogrammererrorØ E.g.,precondi-onviola-ons,
notusingAPIcorrectly
Checked• Anyotherexcep-on• Programmercreatesandhandlescheckedexcep-ons
• Compiler-enforcedcheckingØ Improvesreliability*
• Forcondi-onsfromwhichcallercanreasonablybeexpectedtorecover
Sept30,2016 Sprenkle-CSCI209 35
TypesofUncheckedExcep-ons1. DerivedfromtheclassError
Ø Anylineofcodecangeneratebecauseitisaninternalerror
Ø Don’tworryaboutwhattodoifthishappens2. DerivedfromtheclassRuntimeException
Ø IndicatesabugintheprogramØ FixthebugØ Examples:ArrayOutOfBoundsException, NullPointerException, ClassCastException
Sept30,2016 Sprenkle-CSCI209 36
9/30/16
19
CheckedExcep-ons• Needtobehandledbyyourprogram
Ø Compiler-enforcedØ Improvesreliability*
• Foreachmethod,tellthecompiler:Ø WhatthemethodreturnsØ Whatcouldpossiblygowrong
• Adver9setheexcep-onsthatamethodthrows• Helpsusersofyourinterfaceknowwhatmethoddoesandletsthemdecidehowtohandleexcep-ons
Sept30,2016 Sprenkle-CSCI209 37
Discussion:WhyCheckedandUncheckedExcep-ons?
• Whydowehaveexcep-onsthatthecompilerdoesn’tforcetheprogrammertocheck?Ø Thinkaboutexamplesofuncheckedexcep-ons(ArrayOutOfBoundsException, NullPointerException, ClassCastException)andwhenthoseexcep-onscanoccur
Sept30,2016 Sprenkle-CSCI209 38
9/30/16
20
THROWINGEXCEPTIONS
Sept30,2016 Sprenkle-CSCI209 39
CommonExcep-onsName PurposeIllegalArgumentException Whencallerpassesininappropriate
argumentIllegalStateException Invoca-onisillegalbecauseofreceiving
object’sstate.(Ex:closingaclosedwindow)
• BothinheritfromRuntimeException• Mayseemlikethesecovereverythingbutonlyusedforcertainkindsofillegalargumentsandexcep-ons
• NotusedwhenØ Anullargumentpassedin;shouldbeaNullPointerException
Ø Passininvalidindexforanarray;shouldbeanIndexOutOfBoundsException
Sept30,2016 Sprenkle-CSCI209 40
9/30/16
21
FactorialAlterna-ves
Sept30,2016 Sprenkle-CSCI209 41
public static double factorial( int x ) {if( x < 0 )
return 0.0;double fact = 1.0;while( x > 1 ) {
fact *= x;x--;
}return fact;
}
FactorialAlterna-ves
Sept30,2016 Sprenkle-CSCI209 42
public static double factorial( int x ) {if( x < 0 )
throw new IllegalArgumentException("x" +"must be >= 0");
double fact = 1.0;while( x > 1 ) {
fact *= x;x--;
}return fact;
}
9/30/16
22
FactorialAlterna-ves
Sept30,2016 Sprenkle-CSCI209 43
public static double factorial( int x ) {if( x < 0 )
throw new IllegalArgumentException("x" +"must be >= 0");
double fact = 1.0;while( x > 1 ) {
fact *= x;x--;
}return fact;
}
What are the pros and cons of these approaches?
IllegalArgumentException:Thrown to indicate that a method has been passed an illegal or inappropriate
argument
Note, no throws clause in method signature. Why?
Goal:FailureAtomicity• A\eranobjectthrowsanexcep-on,theobjectshouldbeinawell-defined,usablestateØ Afailedmethodinvoca-onshouldleaveobjectinstatepriortoinvoca-on
• Approaches:Ø Checkparameters/statebeforeperformingopera-on(s)Ø Dothefailure-proneopera-onsfirstØ Userecoverycodeto“rollback”stateØ Applytotemporaryobjectfirst,thencopyovervalues
Sept30,2016 Sprenkle-CSCI209 44
9/30/16
23
Prac-ce
• Howshouldweimplementthismethod?• Whataresomeproblemswecouldface?
Sept30,2016 Sprenkle-CSCI209 45
public void setBirthday(int month, int day) { }
Prac-ce
• Howshouldweimplementthismethod?Ø Ruleofthumb:Handleerrorcheckingfirst
Sept30,2016 Sprenkle-CSCI209 46
public void setBirthday(int month, int day) { }
9/30/16
24
CATCHINGEXCEPTIONS
Sept30,2016 Sprenkle-CSCI209 47
Sept30,2016 Sprenkle-CSCI209 48
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?
9/30/16
25
Sept30,2016 Sprenkle-CSCI209 49
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
}
Sept30,2016 Sprenkle-CSCI209 50
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
9/30/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();}
}Prints out stack trace to method call
that caused the error
Sept30,2016 Sprenkle-CSCI209 52
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
9/30/16
27
Sept30,2016 Sprenkle-CSCI209 53
Thefinally Block
• Allowsyoutocleanupordomaintenancebeforemethodends(onewayortheother)Ø E.g.,closingfilesordatabaseconnec-ons
try {…
} catch (Exception e) {
…}finally {
…}
• Op-onal:addafinallyblocka\erallcatchblocksØ Codeinfinally blockalwaysrunsa\ercodeintry and/orcatchblocks• A\ertry blockfinishesor,ifanexcep-onoccurs,a\erthecatchblockfinishes
FinallyTest.java
Sept30,2016 Sprenkle-CSCI209 54
Prac-ce:try/catch/finally Blocks
try {statement1;statement2;
} catch (EOFException e) {
statement3;statement4;
}finally {
statement5;}
• Whichstatementsrunif:Ø Neitherstatement1norstatement2throwsanexcep-on
Ø statement1throwsanEOFException
Ø statement2throwsanEOFException
Ø statement1throwsanIOException
9/30/16
28
WhattodowithaCaughtExcep-on?• Dumpthestacka\ertheexcep-onoccurs
Ø Whatelsecanwedo?
• Generally,twoop-ons:1. Catchtheexcep-onandrecoverfromit2. Passexcep-onuptowhoevercalledit
Sept30,2016 Sprenkle-CSCI209 55
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 56
9/30/16
29
ProgrammingwithExcep-ons• Excep-onhandlingisslow
• Useonebigtry blockinsteadofnes-ngtry-catch blocksØ SpeedsupExcep-onHandlingØ Otherwise,codegetstoomessy
• Don'tignoreexcep-ons(e.g.,catch blockdoesnothing)Ø Be]ertopassthemalongtohighercalls
Sept30,2016 Sprenkle-CSCI209 57
try {}catch () { }try {}catch () { }
try {try {}catch () { }
}catch () { }
try {……
}catch () { }
Sept30,2016 Sprenkle-CSCI209 58
BenefitsofExcep-ons?
9/30/16
30
Sept30,2016 Sprenkle-CSCI209 59
BenefitsofExcep-ons• Forceerrorchecking/handling
Ø Otherwise,won’tcompileØ Doesnotguarantee“good”excep-onhandling
• EasedebuggingØ Stacktrace
• Separateserror-handlingcodefrom“regular”codeØ ErrorcodeisincatchblocksatendØ Descrip-vemessageswithexcep-ons
• PropagatemethodsupcallstackØ Letwhoever“cares”abouterrorhandleit
• Groupanddifferen-ateerrortypes
JavadocGuidelinesabout@throws• Alwaysreportifthrowcheckedexcep-ons• Reportanyuncheckedexcep-onsthatthecallermightreasonablywanttocatchØ Excep-on:NullPointerExceptionØ Allowscallertohandle(ornot)Ø Documentexcep-onsthatareindependentoftheunderlyingimplementa-on
• Errorsshouldnotbedocumentedastheyareunpredictable
Sept30,2016 Sprenkle-CSCI209 60