+ All Categories
Home > Documents > CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was...

CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was...

Date post: 21-May-2020
Category:
Upload: others
View: 14 times
Download: 0 times
Share this document with a friend
62
CS 360 Programming Languages Introduction to Java
Transcript
Page 1: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

CS360ProgrammingLanguagesIntroductiontoJava

Page 2: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Theplan

• Racketwillreturn!– FinalprojectwillbewritingaRacketinterpreterinJava.

• LecturewillnotdiscusseverysinglefeatureofJava.– Youmayneedtodosomediggingonyourown.– Lotsofhelponline(Googleisyourfriend).

Page 3: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

JavaResources

• Javatutorial– http://docs.oracle.com/javase/tutorial/java

• Javadocumentation– http://docs.oracle.com/javase/8/docs/api

• Andifyou'reconfusedaboutanything,Googlewillfindit.– There'ssomuchJavastuffonthewebbecausemostundergraduate

curriculumsnowteachJavaastheirfirstorsecondlanguage.

Page 4: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Logistics

• WewilluseJavaversion8.

– ThoughprobablymostofthecodeIwillshowiscompatiblebacktoJava6and7.

– Java9wasjustreleasedaboutsixweeksago.

• ManypowerfulIDEsoutthere.

– IwillbeusinganIDEcalledNetBeans,whichisfree.

– Installationinstructionswillbeontheclasswebpage.

Page 5: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

NextAssignments

• Overlappingtimeframesforthelastassignments.• Project4– outtoday,stillinRacket

– Outtoday– DueTueNov14

• Project5– Javawarmupassignment– OutThuNov9– DueTueNov21[daybeforeThanksgivingbreak].

• Project6– Javaproject involvingthreadsandconcurrency– OutTueNov14– DueTueNov28

• Project7– RacketinterpreterinJava.– OutTueNov28– Dueduringfinalexams(probablyTueDec12).

Page 6: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

HistoryofJava

Page 7: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

HistoryofJava

• Javawasfirstusedinthe15th century,inYemen,andquicklyspreadtoEgyptandNorthAfrica.

Page 8: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java
Page 9: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

TheRealHistoryofJava

Page 10: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

TheRealHistoryofJava

• Javaismillionsofyearsoldand135millionpeopleseeJavaeveryday.

Page 11: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java
Page 12: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

TheReal,RealHistoryofJava

• TheJavaprojectwasinitiatedatSunMicrosystemsin1991.– Supposedlynamedafterthelargequantitiesofcoffeethelanguage

designersdrank.

• Originallywasdesignedtobeembeddedinconsumerelectronicdevices,likecableTVset-topboxes,butitwastooadvancedforthecabletelevisionindustryatthetime.

• Languageevolvedintoageneral-purposeprogramminglanguage.

Page 13: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

TheReal,RealHistoryofJava

• JavawasdesignedtouseasyntaxsimilartoCandC++.– Lotswillbefamiliar.

• Javais(almostcompletely)objectoriented.– Alldatatypesareclasses,exceptfortheprimitiveslikeint,long,float,

double,char,boolean.– Allcodeiswritteninsidesomeclass.

• Allfunctionsaremethods(nofree-floatingfunctions).– Singleinheritanceonly(C++allowsmultiple).

• Staticallytyped(likeC++,).

• Hasgenerics (similartoC++templates).

Page 14: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

TheReal,RealHistoryofJava

• SamebasicprogrammingpropertiesasC++.– Mustdeclarevariablesbeforeuse,saywhattypetheyare.– If/else,for,while,do-while,switchworkjustlikeC++.

• Nopointers!– Javausesasimilarideacalledreferences,whichare"safer"than

pointers.

• Allobjectsstoredontheheap(using"new").

• Garbagecollection– Noexplicitallocation/deallocationofmemory.(nomalloc/free)

Page 15: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Definingaclass

• TakealookattheRationalclass.

Page 16: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

• CreateprimitivevariablesjustlikeinC++:– int x=4;– floatf=3.02;– boolean b=true;//notelowercase

• Stringsareobjects,butJavaletsyoucreatethemlikeaprimitive:– Strings="awonderfulstring";

• Allotherobjectsarecreatedusingnew:– ClassName var =newClassName(args);– Constructorautomaticallychosenbasedondatatypesofarguments.

Page 17: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

• Variablesdeclaredinaclassarecalledfields or instancevariables.(likeC++)

• Instancesofaclasshaveonecopyoftheirfieldsorinstancevariables.

• Contrastwithclassvariablesor staticvariables:onecopyofthevariablethatissharedamongallinstancesoftheclass.– Declaredwithstatic keyword.

Page 18: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

• Functionsdeclaredinaclassknownasmethods.

• Instancemethodscanaccessinstancevariables,andarecalledusingC++-likesyntax:– ClassName var = new ClassName();– var.name_of_method(arg1, arg2, ...);

• Classmethodsorstaticmethodsarecalledonthenameoftheclassitself,notaninstanceoftheclass.– ClassName.name_of_instance_method(args);– example: Integer.toString(int), Math.pow(x, y)

Page 19: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Class/Method/VariableVisibility

• public:availableeverywhere• protected:onlyavailablewithintheclassandsubclasses• private:onlyavailablewithintheclass

• SimilartoC++:– Haveanumberofprivateinstancevariablesthatmaintainthe"state"of

theclass.– Haveanumberofpublicmethodsthatarepartoftheclass'sinterface.– Alsocommontohaveprivate"helper"methods.

Page 20: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

• JavatraditionallyusesCamelCase ratherthanseparating_with_underscores.• variablesandmethodsstartwithalowercaseletter.• Classnamesstartwithanuppercaseletter.• "this"worksjustlikeinC++.• Allobjectsbydefaultinheritfromthe"Object"baseclass.

Page 21: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Gettingaprogramstarted

• Eachclassmustgoinitsownfile,whichmustbenamedClassName.java.• Anyclasscanhaveapublicstaticmain()method,whichiswherethe

executionstarts.

Page 22: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Packages

• Java'sstandardlibrary(allthefunctionsthatthelanguagecomeswith)areorganizedintopackages– Ahierarchicalorganizationsystem.

• InJavayou"import"classesfrompackages,whereasinC++you"#include"files.

Page 23: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Collections

• Builtinclassesfor– Lists(ArrayList,LinkedList,…)– Sets(HashSet,…)– Maps(whatJavacallshashtables)(HashMap)

• Alloftheseareparameterizedwithgenerics.– List<Integer>intlist =newList<Integer>();– intlist.add(17);– System.out.println(intlist);//prints[17]

Page 24: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Today'splan

• IntroduceOOPconceptsfromthegroundupusingJava.– Rehashof142-ishthingsbutatadeeperlevelofunderstanding.

• Talkaboutwhy/whenyoushouldorshouldn'tdocertainOOPthings.

• LotsofthingswillbefamiliarfromC++.

• Somethingswillbedifferent.

Page 25: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

public class Point{private int x, y;public Point(int x, int y) { this.x = x; this.y = y;

}public int getX() { return x; }public int getY() { return y; }public void setX(int x) { this.x = x; }public void setY(int y) { this.y = y; }public double distFromOrigin() {return Math.sqrt(x * x + y * y)

}}

Page 26: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Subclassing

• Aclassdefinitionhasasuperclass(Object ifnotspecified)

• Thesuperclassaffectstheclassdefinition:– Classinherits allfielddeclarationsfromsuperclass– Classinherits allprivatemethoddefinitionsfromsuperclass

• Codewithinthesubclasscannotdirectlyaccessanyprivatefieldsormethods.

– Butclasscanoverridemethoddefinitionsasdesired

class ColorPoint extends Point { … }

Page 27: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

public class ColorPoint extends Point{private Color color;public ColorPoint(int x, int y, Color c) {super(x, y); // call the superclass constructorthis.color = c;

}public Color getColor() { return color; }public void setColor(Color c) { this.color = c; }

}

Page 28: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Anobjecthasaclass

• Usinginstanceof canindicate bad OO style.– If you're using it to do something different for different objects types,

you probably meant to write a method and have subclasses override the method.

• instanceof is an example of using reflection– Reflection is the ability for a computer program to be able to

examine its structure and behavior at run-time.

Point p = new Point(0, 0);ColorPoint cp = new ColorPoint(0, 0, Color.red)

/* instanceof is a keyword that returns trueif a variable is an instance of a class. */

p instanceof Point // truecp instanceof ColorPoint // truecp instanceof Point // true

Page 29: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Whysubclass?

• InsteadofcreatingColorPoint,couldaddmethodstoPoint– Thatcouldmessupotherusersandsubclassers ofPoint

public class Point {private int x, y;private Color color; …

public Point(x, y) { // what does color get set to?

}}

Page 30: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Whysubclass?

• Insteadofsubclassing Point,couldcopy/pastethemethods– Meansthesamethingif youdon'tuseinstanceof,butofcoursecode

reuseisnice

public class ColorPoint {private int x, y;private Color color; …

}

ColorPoint cp = new ColorPoint( whatevs )if (cp instanceof Point) {// do pointy things

}

Page 31: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Whysubclass?

• Insteadofsubclassing Point,coulduseaPoint instancevariableinsideofColorPoint.– DefinemethodstosendsamemessagetothePoint– Thisiscalledobjectcomposition;expressesa"hasa"relationship.– ButforColorPoint,subclassing makessense:lessworkandcanuseaColorPoint wherevercodeexpectsaPoint

public class ColorPoint {private Point point;private Color color;public setX(int x) { point.setX(x); }…

}

Page 32: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Is-avs has-a

• OObeginnerstendtooveruseinheritance(theis-arelationship).

• OOinheritanceisnotoriouslytrickytogetrightsometimes(e.g.,writingmethodsthattestforequality)– boolean equals(Pointa,Pointb)– Whatifa&bcanbePointsorColorPoints?

• Manyreal-worldrelationshipscanbeexpressedusingis-aorhas-a,evenifthemostnaturalwayseemstobeis-a.– ColorPoint couldbewrittenusingobjectcomposition.

Page 33: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Circleandellipseproblem

• WhatshouldtherelationshipbebetweenaCircleclassandanEllipseclass?

Page 34: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Circleandellipseproblem

• Circlesarespecifictypesofellipses,soaCircleis-a Ellipse.

public class Ellipse {

private int radiusX, int radiusY;

public void setRadiusX(int rx) { radiusX = rx; }

public void setRadiusX(int rx) { radiusY = ry; }

public int getRadiusX() { return radiusX; }

public int getRadiusY() { return radiusY; }

}

public class Circle extends Ellipse {

}

Page 35: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Circleandellipseproblem

• Circlesarespecifictypesofellipses,soaCircleis-a Ellipse.

• ButnowCirclehasasetRadiusX()method.

• Furthermore,whatwouldthatmethod'simplementationlooklike?

Page 36: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Circleandellipseproblem

• Differentsolution:makeEllipseasubclassofCircle.– "AnEllipseisaCirclewithanextraradiusfield."

public class Circle {

private int radius;

public void setRadius(int r) { radius = r; }

public int getRadius() { return radius; }

}

public class Ellipse extends Circle {

private int radiusY;

// assume existing radius is for X dimension.

}

Page 37: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Circleandellipseproblem

• Differentsolution:makeEllipseasubclassofCircle.– "AnEllipseisaCirclewithanextraradiusfield."

• Justasmanyproblemshere:

• WhatdoesitmeanwhenanEllipsecallsCircle'ssetRadius orgetRadiusmethod(whichradius?)

Page 38: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Onesolution:Immutability

• LetCircleinheritfromEllipseandeliminatemutator methods.

public class Ellipse {

private int radiusX, int radiusY;

public int getRadiusX() { return radiusX; }

public int getRadiusY() { return radiusY; }

}

public class Circle extends Ellipse { … }

• Circle still has two radius accessor methods.• As long as Circle's constructor forces radiusX = radiusY, there's no

way to violate that constraint later.

Page 39: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Othersolutions

• Let Circle and Ellipse inherit from some common superclass (rather than one from the other).

• Let setRadiusX() return success or failure.

• Drop inheritance entirely.

• Drop Circle; let users (manually) handle circles as instances of Ellipse.

Page 40: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Whatinheritancereallyisfor

• Inheritancegetsyouintotroublewhenitseemsliketherelationshipis"is-a,"butitactuallyis"is-a-restricted-version-of."– CircleandEllipse– PersonandToddler

• CertainlyaToddlerisaPerson.• ButwhatifaPersonhasamethodcalledwalk(int distance).• Toddlerscan'twalk!

• Inheritanceshouldbeusedtoaddextradetailtoasuperclass(e.g.,aMonkeyisanAnimal),nottorestrictfunctionality.– ColorPoint is(probably)finetoinheritfromPoint

Page 41: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Trythisoneout

• IwanttodeclareaclassThreeDPoint.

• ShouldthisinheritfromPoint?– Whataretheprosandcons?

Page 42: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Somethingdifferent:Methodoverriding

• InOOP,asubclassmayoverrideamethodfromasuperclass.• Justre-definethemethodinthesubclass.

Page 43: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

InC++,whatdoesthisdo?class Base {

public: int f() { return 1; } };

class Derived: public Base {

public: int f() { return 2; } };

int main() {

Base b;

Derived d;

cout << b.f() << endl;

cout << d.f() << endl;

b = d;

cout << b.f() << endl;

Base *b2 = &d;

cout << b2->f() << endl;

}

Page 44: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Base *b2 = &d;cout << b2->f() << endl;

• Withapointertoanobject,acalltoamethodofthatobjectcallstheversionofthemethodspecifiedbythetypeofthepointer,notthetypeoftheobjectbeingpointedto.

• CanbechangedwiththeC++keywordvirtual.

• Withapointertoanobject,acalltoavirtualmethodofthatobjectcallstheversionofthemethodspecifiedbythetypeoftheobjectbeingpointedto.

Page 45: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

InC++,whatdoesthisdo?class Base {

public: virtual int f() { return 1; } };

class Derived: public Base {

public: int f() { return 2; } };

int main() {

Base b;

Derived d;

cout << b.f() << endl;

cout << d.f() << endl;

b = d;

cout << b.f() << endl;

Base *b2 = &d;

cout << b2->f() << endl;

}

Page 46: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

• Thekeyideahereiscalleddynamicdispatch:– Selectingwhichimplementationofapolymorphicoperationtocallat

run-time,ratherthancompile-time.• Thisistheoppositeofwhatwe'velearnedaboutlexical(static)scope:

– Inlexicalscope,wealwaysknowatcompile-timewhatvariableswillbereferredtoandwhatfunctionswillbecalled.

• WithOOP,itispossibleforavariabletorefertoanobjectwhosetypeisuncertainatcompiletime.

Base b;

Derived d;

Base *b2 = nullptr;

if (rand() > 0.5))

b2 = &b;

else

b2 = &d;

b2->f();

Page 47: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Javavirtualmethods

• InJava,allmethodsarevirtual.– Thisbehaviorcannotbechanged.– Ifasubclassneedstocallasuperclass'sversionofanoverriddenmethod

fromasubclass,thereisthesuper keyword:

public class Base {

public int f() { return 1; } }

public class Derived extends Base {

public int f() { return 2 + super.f(); } }

Page 48: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Javavirtualmethods

public class ThreeDPoint extends Point{private int z;

// override distFromOrigin in Pointpublic double distFromOrigin() {return Math.sqrt(getX()*getX() + getY()*getY() + z*z;

}}

Page 49: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

JavaI/O

• Mainwayofoutputtingtothescreen:

• System.out.println(x);– takesoneargumentofanytype– ifxisanobject,itstoString()methodwillbeautomaticallycalledto

convertittoaString.– alsoSystem.err.println(x);

– System.out isanOutputStream object(similartocout inC++)

Page 50: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

JavaI/O

• Thereareabout50bazillionwaystodoinputinJava.• Easiestway:

– import java.util.*;– Scanner scanner = new Scanner(System.in)

• System.in isanInputStream object(similartocin inC++)– Nowcallanyofthefollowing:– scanner.nextInt() [ornextLong(),nextFloat(),etc]

• allofthesestopatthefirstwhitespacefound– scanner.nextLine()

• readsawholeline,returnsaString

Page 51: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Trythis

• Makeaprogramthatreadsinintegersfromthekeyboarduntilyouenter-1.

Page 52: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Collections

• Javahasmanycollectionclasses.– ArrayList,HashSet,HashMap mostcommon.– Veryfewcaseswhereyouneed"real"arrays;usingArrayList ismuch

morecommon.

• SyntaxissimilartoC++templates– e.g.,C++'svector,set,andmap

• Gotcha:OnlyobjectscanbestoredinJava'scollectionclasses.– Noints,floats,booleans,doubles,etc inArrayLists!– Javahas"wrapper"classesInteger,Float,Boolean,Doublethatyouuse

instead,andJavadoestheconversionforyou.

Page 53: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

ArrayList (exampleforints)

• Creation– List<Integer> list = new ArrayList<Integer>();

• Putstuffin– list.add(x); // adds x to end by default– list.add(i, x); // inserts x at list[i]– list.set(i, x); // changes list[i] to x

• Getstuffout– list.get(i); // returns list[i]

• Other stuff– list.size(), list.contains(x), list.indexOf(x), list.remove(i),

Page 54: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Enhancedforloop

for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));

}

for (int x : list) {System.out.println(x);

}

Page 55: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Trythis

• Makeaprogramthatreadsinintegersfromthekeyboarduntilyouenter-1.• Addalltheintegers(asthey'reentered)toanArrayList.• Printoutalltheintegers.Trythistwoways:

– System.out.println(list);– Withtheenhancedforloop.

Page 56: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Trythis

• Makeaprogramthatreadsinintegersfromthekeyboarduntilyouenter-1.• Addastaticmethodfib(n)thatcomputesthen'th Fibonaccinumber.Write

thisthestandard(slow,recursive)way.• PrintouttheFibonaccivalueofeachnumberasthey'reentered.

– WhatisthemaxFibonacci#youcancomputebeforeyougetanerror?

Page 57: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

HashMaps

• Java'shasafewhashtable classes.• MostcommonisHashMap.

• TheJavalanguagewasconstructedwithhashtables inmind.• TheObjectclasshasahashCode()method.

– Becauseallobjectsinherit(directlyorindirectly)fromObject,allclasseshaveahashCode()method!

• Ifyouevermakeaclassthatyouwanttouseasthekeyofahashtable,youshouldoverridethehashCode()andequals()methods.– Don'tworryaboutthisatthemoment.

Page 58: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

HashMap (exampleforStringmaptoint)

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

• Putstuffin– map.put(s, i); // associates key s with value i

• Getstuffout– map.get(s); // returns whatever value s is associated with

• Otherstuff– map.size(), map.containsKey(s), map.keySet(), map.remove(s)

Page 59: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Enhancedforloop

You can use the enhanced for loop to iterate through a map:

for (String key : map.keySet()) {int value = map.get(key);// do something with key and/or value

}

Page 60: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

Trythis:memoized FibonacciinJava

• AddaHashMap<Integer,Integer>asastaticfieldtoyourclass.– ThiswillstorethecachedFibonaccivalues.

• AlteryourFibonaccimethodsoitdoesthefollowing:– Forfib(n):– ifn=0orn=1,returnn– Checkifnisakeyinthehashtable.

• Ifitis,getthecorrespondingvalueandreturnit.• Ifit'snot,then

– computev=fib(n-1)+fib(n-2)– putthemappingfromntovinthehashtable– returnv

Page 61: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

HashSets

• ASet(ADT)isanunordered collectionofitems.– AListisanordered collectionofitems.

• JavahasaHashSet classthatimplementsthisADT.• SimilartoC++'sstd::setclass.

Page 62: CS 360 Programming Languages Introduction to Java · The Real, Real History of Java • Java was designed to use a syntax similar to C and C++. –Lots will be familiar. • Java

HashSet (exampleforints)

• Creation– HashSet<Integer> set = new HashSet<Integer>();

• Putstuffin– set.add(x); // adds x to the set

• Testifsomethingisintheset– set.contains(x); // returns true or false

• Remove something from the set– set.remove(x);

• Other stuff– set.size(), set.isEmpty(), set.clear()


Recommended