Top Banner
The Java Library (slides adapted from D. Millard) Thai Son Hoang ECS, University of Southampton, U.K. COMP1202 2nd November 2020
38

The Java Library - University of Southampton

Apr 03, 2022

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: The Java Library - University of Southampton

The Java Library(slides adapted from D. Millard)

Thai Son Hoang

ECS, University of Southampton, U.K.

COMP12022nd November 2020

Page 2: The Java Library - University of Southampton

Outline

RecapEncapsulationConstructorsLoopsArraysArrayListsIterators

The Java LibraryImplementation vs. InterfaceExample 1 – StringsExample 2 – Hashmap

Summary

ReadingsI Chapter 4.12 and 4.14.7 of Barnes and Kölling [2016]

,T.S. Hoang 2/40

Page 3: The Java Library - University of Southampton

Outline

RecapEncapsulationConstructorsLoopsArraysArrayListsIterators

The Java LibraryImplementation vs. InterfaceExample 1 – StringsExample 2 – Hashmap

Summary

,T.S. Hoang 4/40

Page 4: The Java Library - University of Southampton

Encapsulation (1/3)public class Student {

i n t age = 20;

// code omitted

public s t a t i c void main(String[] args){Student s1 = new Student();System.out.println(s1.getAge());

}

public i n t getAge(){return age;

}

}

Take this exampleclass where age ismodelled as an int

,T.S. Hoang 5/40

Page 5: The Java Library - University of Southampton

Encapsulation (2/3)public class Student {

//int age = 20;Calendar dateOfBirth;

//code omitted

public s t a t i c void main(String[] args){Student s1 = new Student();System.out.println(s1.getAge());

}

//public int getAge(){// return age;//}

public i n t getAge(){Calendar rightNow = Calendar.getInstance();i n t a = calculateAge(rightNow, dateofBirth);return a;

}}

Take this exampleclass where age ismodelled as an int

We might changethe way that age isimplemented – e.g.to make it based onthe current date.Because we used anAccessor we do notneed to alter main.

,T.S. Hoang 6/40

Page 6: The Java Library - University of Southampton

Encapsulation (3/3)public class Student {

//int age = 20;protected Calendar dateOfBirth;

//code omitted

public s t a t i c void main(String[] args){Student s1 = new Student();System.out.println(s1.getAge());

}

//public int getAge(){// return age;//}

public i n t getAge(){Calendar rightNow = Calendar.getInstance();i n t a = calculateAge(rightNow, dateofBirth);return a;

}}

The protected keywordtells Java that only meth-ods in this class* can ac-cess this variable.

*and its sub-classes, butwe’ll come to that later inthe course. . .

And yes, public meansthe opposite – that allother methods can ac-cess it!

,T.S. Hoang 7/40

Page 7: The Java Library - University of Southampton

Constructorspublic class Student {

protected age;

public Student() {age = 20;

}

public Student( i n t a) {age = a;

}

public s t a t i c void main(String[] args){Student s1 = new Student(19);System.out.println(s1.getAge());

}

//code omitted}

Constructor Rules:I Must have the

same name as theclass

I Does not need areturn type

I Can takeparameters

I Can be overloadedI Are invoked at the

point of creationusing the newkeyword

,T.S. Hoang 8/40

Page 8: The Java Library - University of Southampton

Varieties of Loopsi n t i = 0;while(i < 10){

System.out.println(i);i++;

}

i n t i = 0;do {

System.out.println(i);i++;

} while (i < 10);

for ( i n t i = 0; i < 10; i++){

System.out.println(i);}

Initialisation Condition State ChangeA convenience loopfor when we know itadvance how manytimes we want to iterate.Loops zero or moretimes.

Condition is checked atend. Loops one or moretimes.

Condition is checked atstart. Loops zero ormore times.

,T.S. Hoang 9/40

Page 9: The Java Library - University of Southampton

Arrays

numStore

i n t[]

0 1 2 3 4 5 6 7 8

[ ]77

i n t[] numStore;numStore = new i n t[9];numStore[0] = 77;System.out.println(numStore[0]);

DeclarationInstantiationAssignmentRetrieval

,T.S. Hoang 10/40

Page 10: The Java Library - University of Southampton

Iterating Over an Arrayi n t numStore = new i n t[9];//some missing code to fill the array with values

for ( i n t i = 0; i < 9; i++){System.out.print("Number at position " + i);System.out.println(" is " + numStore[i]);

}

Iterating over an arrayis so common that Javanow includes a loopspecifically to do it.

i n t numStore = new i n t[9];//some missing code to fill the array with values

for ( i n t n : numStore){System.out.println("Number is " + n);

}

Like the for loop the ‘foreach’ loop is a shortcut,that is a bit neater thanwriting the code the longway.But it can only be usedfor access (e.g. n++would not increment thevalue in the array)And it hides the currentindex

,T.S. Hoang 11/40

Page 11: The Java Library - University of Southampton

Arrays vs. ArrayLists

ArraysCat[] catArray;catArray = new Cat[10];

catArray[0] = moggy1;catArray[1] = moggy2;

callMethodOn(catArray[1]);

catArray[0] = nul l;

ArrayListsArrayList catAList;catAList = new ArrayList();

catAList.add(moggy1);catAList.add(moggy2);

callMethodOn(catAList.get(1));

catAList.remove(moggy1);

Declaration

Insertion

Access

Removal

,T.S. Hoang 12/40

Page 12: The Java Library - University of Southampton

Generics (1/2)ArrayList kennel = new ArrayList();

kennel.add(new Dog("Rover"));kennel.add(new Dog("Fido"));kennel.add(new Dog("Patch"));kennel.add(new Cat("Mr Tiddles"));

for( i n t i = 0; i < kennel.size(); i++) {kennel.get(i).bark();

}

ArrayLists store objects ofany type

Which means we can mixup the types of objects inthe ArrayList

Which may cause problemslater if we make assump-tions about what is in there!

In fact this code will notcompile, because Javadoes not know what is inthe ArrayList, and thereforewill not let you call bark onit

,T.S. Hoang 13/40

Page 13: The Java Library - University of Southampton

Generics (2/2)

ArrayList<Dog> kennel = new ArrayList<Dog>();

kennel.add(new Dog("Rover"));kennel.add(new Dog("Fido"));kennel.add(new Dog("Patch"));kennel.add(new Cat("Mr Tiddles"));

for( i n t i = 0; i < kennel.size(); i++) {kennel.get(i).bark();

}

It would be better if wecould ensure that the Ar-rayList only containedDogs in the first place

This is easily donebecause ArrayList usesa mechanism calledgenerics.We can specify the typeallowed when we createthe ArrayList.

Now Java will only allowus to add things of typeDog. So this line willforce a compile time er-ror

,T.S. Hoang 14/40

Page 14: The Java Library - University of Southampton

Iterator (1/2)ArrayList<Dog> kennel = new ArrayList<Dog>();

kennel.add(new Dog("Rover"));kennel.add(new Dog("Fido"));kennel.add(new Dog("Patch"));

for( i n t i = 0; i < kennel.size(); i++) {kennel.get(i).bark();

}

Iterator<Dog> it = kennel.iterator();

while(it.hasNext()) {it.next().bark();

}

1) They are neater, and neatcode is easier to read and un-derstand

2) They decouple the loopfrom the collection (noticethat in the loop we do not ref-erence the ArrayList at all)This means we could passthe iterator to a method – andthat method does not evenneed to know what the collec-tion is!

,T.S. Hoang 15/40

Page 15: The Java Library - University of Southampton

Iterators (2/2)public void makeThemBark( Iterator<Dog> it) {

while (it.hasNext()) {it.next().bark();

}

}

1) They are neater, and neat code iseasier to read and understand

2) They decouple the loop from thecollection (notice that in the loop we donot reference the Arraylist at all)This means we could pass the iteratorto a method – and that method doesnot even need to know what the col-lection is!

,T.S. Hoang 16/40

Page 16: The Java Library - University of Southampton

LibraryI The java library is full of helpful classes

I Like ArrayListI What does the inside of an ArrayList look like?

I How does it handle the resizing?

I How does it know when the throw an error?

I How does it handle renumbering when removing elements?

I But they are implementation details.

,T.S. Hoang 18/40

Page 17: The Java Library - University of Southampton

Implementation vs. InterfaceI Because of encapsulation all we need to know

to use the ArrayList class, and the other library classesis what their interface is

I A Class’ interface is how we interact with the classI It’s public variables and methods

I what methods we can call

I what they do

I what they will return

,T.S. Hoang 19/40

Page 18: The Java Library - University of Southampton

ImportingI Library classes must be imported using an import statement

import java.util.ArrayList;

public class myClass{

ArrayList<String> arrl;arrl = new ArrayList<String>;

public s t a t i c void main(String[] args){//code omitted

}}

,T.S. Hoang 20/40

Page 19: The Java Library - University of Southampton

Importing packagesI Classes are organised in packages.

I Single class may be imported:

import java.util.ArrayList;

I Whole package can be imported:

import java.util.*;

,T.S. Hoang 21/40

Page 20: The Java Library - University of Southampton

Where is the Library?I All library classes are included in the Java runtime and

development environments

I All the documentation is available online:I https://docs.oracle.com/en/java/javase/14/docs/

api/index.html

,T.S. Hoang 22/40

Page 21: The Java Library - University of Southampton

,T.S. Hoang 23/40

Page 22: The Java Library - University of Southampton

,T.S. Hoang 24/40

Page 23: The Java Library - University of Southampton

,T.S. Hoang 25/40

Page 24: The Java Library - University of Southampton

Outline

RecapEncapsulationConstructorsLoopsArraysArrayListsIterators

The Java LibraryImplementation vs. InterfaceExample 1 – StringsExample 2 – Hashmap

Summary

,T.S. Hoang 26/40

Page 25: The Java Library - University of Southampton

StringsI Strings are actually objects

I Did you notice we always use a capital S like other classes?

I You don’t need to import themI they are from the automatically imported from java.lang.*;

I As is System as in System.out.println()

,T.S. Hoang 27/40

Page 26: The Java Library - University of Southampton

A word about comparing Strings

i f (input == "hello") { // Tests identity//code here

}

i f (input.equals("hello")) { // Tests Equality//code here

}

I You probably mean to compare strings using .equals.

I And you should always use .equals.

,T.S. Hoang 28/40

Page 27: The Java Library - University of Southampton

identity vs equality (1/4)

String name1 = "Harry";String name2 = "Tom";

I name1 == name2: false(different addresses)

I name1.equals(name2): false(different values)

name1

String

name2

String

Harry Tom

,T.S. Hoang 29/40

Page 28: The Java Library - University of Southampton

identity vs equality (2/4)

String name1 = "Harry";String name2 = "Harry";

I name1 == name2: true(same address)

I name1.equals(name2): true(same value)

name1

String

name2

String

Harry

,T.S. Hoang 30/40

Page 29: The Java Library - University of Southampton

identity vs equality (3/4)

String name1 = "Harry";String name2 = new

String("Harry");

I name1 == name2: false(different addresses)

I name1.equals(name2): true(same value)

name1

String

name2

String

Harry Harry

,T.S. Hoang 31/40

Page 30: The Java Library - University of Southampton

identity vs equality (4/4)

String name1 = "Harry";String name2 = name1;

I name1 == name2: true(same address)

I name1.equals(name2): true(same value)

name1

String

name2

String

Harry

,T.S. Hoang 32/40

Page 31: The Java Library - University of Southampton

Outline

RecapEncapsulationConstructorsLoopsArraysArrayListsIterators

The Java LibraryImplementation vs. InterfaceExample 1 – StringsExample 2 – Hashmap

Summary

,T.S. Hoang 33/40

Page 32: The Java Library - University of Southampton

Maps

Name Number

Alfie 407351

Jenny 763412

... ...

I Maps are a collection type thatmap a key to a value

I put("Alfie", "407351");

I put("Jenny", "763412");

I and so on ...

,T.S. Hoang 34/40

Page 33: The Java Library - University of Southampton

LookupI Lookup: supplying the key and having the value returned

String num = myHashMap.get("Alfie");

Name Number

Alfie 407351

Jenny 763412

... ...

,T.S. Hoang 35/40

Page 34: The Java Library - University of Southampton

Bringing it together . . .import java.util.HashMap;

//code omitted

HashMap<String, Integer> marks;marks = new HashMap<String, Integer>();

marks.put("Alice", 75);marks.put("Bob", 62);marks.put("Colin", 68);

System.out.println("Bob got " +marks.get("Bob"));

What is this?HashMap is a genericclass, this means weshould tell it what two typesit maps together

What is happening here?

This is autoboxing –the ints are automaticallyturned into Integers for us

Which type of String com-parison is being used?

Equality (not Identity). It isusing the .equals method

,T.S. Hoang 36/40

Page 35: The Java Library - University of Southampton

Outline

RecapEncapsulationConstructorsLoopsArraysArrayListsIterators

The Java LibraryImplementation vs. InterfaceExample 1 – StringsExample 2 – Hashmap

Summary

,T.S. Hoang 38/40

Page 36: The Java Library - University of Southampton

SummaryI Implementation vs. Interface

I Strings

I HashMaps

,T.S. Hoang 39/40

Page 38: The Java Library - University of Southampton

References I

I David J. Barnes and Michael Kölling. Objects First with Java: APractical Introduction using BlueJ.Pearson, sixth edition edition, 2016 (Chapter 4.12 and 4.14.7)

David J. Barnes and Michael Kölling. Objects First with Java: APractical Introduction using BlueJ. Pearson, sixth edition edition,2016.

,T.S. Hoang 1/1