+ All Categories
Home > Education > 4 gouping object

4 gouping object

Date post: 01-Nov-2014
Category:
Upload: robbie-akachopa
View: 184 times
Download: 0 times
Share this document with a friend
Description:
Materi Kuliah Pemrograman Beorientasi Object (PBO) - Teknik Informatika Universitas Bengkulu @2013/2014 - Endina Putri Purwandari, S.T., M.Kom - by:akachopa [ www.akachopa.com ]
Popular Tags:
87
Grouping objects Indefinite iteration - the while loop
Transcript
Page 1: 4 gouping object

Grouping objects

Indefinite iteration - the while loop

Page 2: 4 gouping object

2

Konsep Penting

• Collections • Loops • Iterators • Arrays

Page 3: 4 gouping object

3

The requirement to group objects

• Many applications involve collections of objects: – Personal organizers. – Library catalogs. – Student-record system.

• The number of items to be stored varies. – Items added. – Items deleted.

Page 4: 4 gouping object

4

A personal notebook

• Notes may be stored. • Individual notes can be viewed. • There is no limit to the number of

notes. • It will tell how many notes are

stored. • Explore the notebook1 project.

Page 5: 4 gouping object

5

Class libraries

• Collections of useful classes. • Java calls its libraries, packages. • Grouping objects is a recurring

requirement. – The java.util package contains

classes for doing this.

Page 6: 4 gouping object

6

import java.util.ArrayList; /** * ... */ public class Notebook { // Storage for an arbitrary number of notes. private ArrayList notes; /** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList(); } ... }

Page 7: 4 gouping object

7

Object structures with collections

Page 8: 4 gouping object

8

Features of the collection

• It increases its capacity as necessary. • It keeps a private count:

– size() accessor.

• It keeps the objects in order. • Details of how all this is done are

hidden. – Does that matter? Does not knowing how

prevent us from using it?

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 9: 4 gouping object

9

Using the collection

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

public class MusicOrganizer { private ArrayList<String> files; ... public void addFile(String filename) { files.add(filename); } public int getNumberOfFiles() { return files.size(); } ... }

Adding a new file

Returning the number of files (delegation)

Page 10: 4 gouping object

10

Index numbering

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 11: 4 gouping object

11

Retrieving an object

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Could be invalid ! public void listFile(int index) { String filename = files.get(index); System.out.println(filename); }

Print the file name Retrieve the file name

Page 12: 4 gouping object

12

Retrieving an object

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Index validity checks public void listFile(int index) { if(index >= 0 && index < files.size()) { String filename = files.get(index); System.out.println(filename); } else { // This is not a valid index. } }

Retrieve and print the file name

Needed? (Error message?)

Page 13: 4 gouping object

13

Removal may affect numbering

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 14: 4 gouping object

14

The general utility of indices

• Using integers to index collections has a general utility: – ‘next’ is: index + 1 – ‘previous’ is: index – 1 – ‘last’ is: list.size() – 1 – ‘the first three’ is: the items at indices 0, 1, 2

• We could also think about accessing items in sequence: 0, 1, 2, …

Page 15: 4 gouping object

15

Review

• Collections allow an arbitrary number of objects to be stored.

• Class libraries usually contain tried-and-tested collection classes.

• Java’s class libraries are called packages.

• We have used the ArrayList class from the java.util package.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 16: 4 gouping object

16

Review

• Items may be added and removed. • Each item has an index. • Index values may change if items are

removed (or further items added). • The main ArrayList methods are add, get, remove and size.

• ArrayList is a parameterized or generic type.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 17: 4 gouping object

17

Interlude: Some popular errors...

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 18: 4 gouping object

18

/** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + " files"); } }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

What’s wrong here?

Page 19: 4 gouping object

19

/** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0); { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

This is the same as before!

Page 20: 4 gouping object

20

/** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0) ; { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

This is the same again

Page 21: 4 gouping object

21

/** * Print out info (number of entries). */ public void showStatus() { if(files.size() == 0) { ; } { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

and the same again…

Page 22: 4 gouping object

22

/** * Print out info (number of entries). */ public void showStatus() { if(isEmpty = true) { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

This time I have a boolean field called ‘isEmpty’... What’s wrong here?

Page 23: 4 gouping object

23

/** * Print out info (number of entries). */ public void showStatus() { if(isEmpty == true) { System.out.println("Organizer is empty"); } else { System.out.print("Organizer holds "); System.out.println(files.size() + "files"); } }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

This time I have a boolean field called ‘isEmpty’... The correct version

Page 24: 4 gouping object

24

/** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size() == 100) files.save(); // starting new list files = new ArrayList<String>(); files.add(filename); }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

What’s wrong here?

Page 25: 4 gouping object

25

/** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size == 100) files.save(); // starting new list files = new ArrayList<String>(); files.add(filename); }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

This is the same.

Page 26: 4 gouping object

26

/** * Store a new file in the organizer. If the * organizer is full, save it and start a new one. */ public void addFile(String filename) { if(files.size == 100) { files.save(); // starting new list files = new ArrayList<String>(); } files.add(filename); }

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

The correct version

Page 27: 4 gouping object

Grouping objects

Collections and the for-each loop

Page 28: 4 gouping object

28

Main concepts to be covered

• Collections • Loops: the for-each loop

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 29: 4 gouping object

29

Iteration

• We often want to perform some actions an arbitrary number of times. – E.g., print all the file names in the organizer.

How many are there?

• Most programming languages include loop statements to make this possible.

• Java has several sorts of loop statement. – We will start with its for-each loop.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 30: 4 gouping object

30

Iteration fundamentals

• We often want to repeat some actions over and over.

• Loops provide us with a way to control how many times we repeat those actions.

• With collections, we often want to repeat things once for every object in a particular collection.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 31: 4 gouping object

31

For-each loop pseudo code

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

for(ElementType element : collection) { loop body }

For each element in collection, do the things in the loop body.

loop header for keyword

Statement(s) to be repeated

Pseudo-code expression of the actions of a for-each loop

General form of the for-each loop

Page 32: 4 gouping object

32

Iterating over a collection

Iterator it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object }

java.util.Iterator Returns an Iterator

object

public void listNotes() { Iterator it = notes.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }

Page 33: 4 gouping object

33

Review

• Loop statements allow a block of statements to be repeated.

• The for-each loop allows iteration over a whole collection.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 34: 4 gouping object

Grouping objects

Indefinite iteration - the while loop

Page 35: 4 gouping object

35

Main concepts to be covered

• The difference between bounded and unbounded iteration.

• The while loop

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 36: 4 gouping object

36

Search tasks are indefinite

• We cannot predict, in advance, how many places we will have to look.

• Although, there may well be an absolute limit – i.e., checking every possible location.

• ‘Infinite loops’ are also possible. – Through error or the nature of the task.

Page 37: 4 gouping object

37

The while loop

• A for-each loop repeats the loop body for each object in a collection.

• Sometimes we require more variation than this.

• We use a boolean condition to decide whether or not to keep going.

• A while loop provides this control.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 38: 4 gouping object

38

While loop pseudo code

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

while(loop condition) { loop body }

while we wish to continue, do the things in the loop body

boolean test while keyword

Statements to be repeated

Pseudo-code expression of the actions of a while loop

General form of a while loop

Page 39: 4 gouping object

39

Looking for your keys

while(the keys are missing) { look in the next place; }

Or: while(not (the keys have been found)) { look in the next place; }

Page 40: 4 gouping object

40

Looking for your keys

boolean searching = true; while(searching) { if(they are in the next place) { searching = false; } }

Suppose we don’t find them?

Page 41: 4 gouping object

41

A Java example

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

/** * List all file names in the organizer. */ public void listAllFiles() { for(String filename : files) { System.out.println(filename); } }

for each filename in files, print out filename

Page 42: 4 gouping object

42

A Java example

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

/** * List all file names in the organizer. */ public void listAllFiles() { int index = 0; while(index < files.size()) { String filename = files.get(index); System.out.println(filename); index++; } }

Increment index by 1

while the value of index is less than the size of the collection, get and print the next file name, and then increment index

Page 43: 4 gouping object

43

for-each versus while

• for-each: – easier to write. – safer: it is guaranteed to stop.

• while: – we don’t have to process the whole

collection. – doesn’t even have to be used with a

collection. – take care: could be an infinite loop.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 44: 4 gouping object

44

Finishing a search

• How do we finish a search? • Either there are no more items

to check: index >= files.size()

• Or the item has been found: found == true found ! searching

Page 45: 4 gouping object

45

Continuing a search

• With a while loop we need to state the condition for continuing:

• So the loop’s condition will be the opposite of that for finishing: index < files.size() && ! found index < files.size() && searching

• NB: ‘or’ becomes ‘and’ when inverting everything.

Page 46: 4 gouping object

46

Searching a collection

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

int index = 0; boolean found = false; while(index < files.size() && !found) { String file = files.get(index); if(file.contains(searchString)) { // We don't need to keep looking. found = true; } else { index++; } } // Either we found it at index, // or we searched the whole collection.

Page 47: 4 gouping object

47

The String class

• The String class is defined in the java.lang package.

• It has some special features that need a little care.

• In particular, comparison of String objects can be tricky.

Page 48: 4 gouping object

48

Side note: String equality

if(input == "bye") { ... } if(input.equals("bye")) { ... }

Always use .equals for text equality.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

tests identity

tests equality

Page 49: 4 gouping object

49

Identity vs equality 1

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Jill”

:Person

Page 50: 4 gouping object

50

Identity vs equality 2

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

Page 51: 4 gouping object

51

Identity vs equality 3

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

Page 52: 4 gouping object

52

Identity vs equality (Strings)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

"bye"

:String

input

"bye"

:String

String input = reader.getInput(); if(input == "bye") { ... }

== ?

(may be) false!

== tests identity

Page 53: 4 gouping object

53

Identity vs equality (Strings)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

"bye"

:String

input

"bye"

:String

String input = reader.getInput(); if(input.equals("bye")) { ... }

equals ?

true!

equals tests equality

Page 54: 4 gouping object

54

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 55: 4 gouping object

Grouping objects

Iterators

Page 56: 4 gouping object

Iterator and iterator()

• Collections have an iterator() method.

• This returns an Iterator object. • Iterator<E> has three methods:

– boolean hasNext() – E next() – void remove()

Page 57: 4 gouping object

57

Using an Iterator object

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Iterator<ElementType> it = myCollection.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object }

java.util.Iterator returns an Iterator object

public void listAllFiles() { Iterator<Track> it = files.iterator(); while(it.hasNext()) { Track tk = it.next(); System.out.println(tk.getDetails()); } }

Page 58: 4 gouping object

58

Iterator mechanics

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 59: 4 gouping object

59 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element

myList:List

:Element :Element

:Iterator

myList.iterator()

:Element

Page 60: 4 gouping object

60 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

:Iterator

hasNext()? ✔ next()

Element e = iterator.next();

:Element

:Iterator

myList:List

Page 61: 4 gouping object

61 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

hasNext()? ✔ next()

:Element

:Iterator :Iterator

myList:List

Page 62: 4 gouping object

62 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

hasNext()? ✔ next()

:Element

:Iterator :Iterator

myList:List

Page 63: 4 gouping object

63 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

hasNext()? ✗

:Element

:Iterator

myList:List

Page 64: 4 gouping object

64

Index versus Iterator

• Ways to iterate over a collection: – for-each loop.

• Use if we want to process every element.

– while loop. • Use if we might want to stop part way through. • Use for repetition that doesn't involve a collection.

– Iterator object (new). • Use if we might want to stop part way through (with while). • Often used with collections where indexed access is not

very efficient, or impossible. • Use to remove from a collection.

• Iteration is an important programming pattern. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 65: 4 gouping object

65

Removing from a collection

Iterator<Track> it = tracks.iterator(); while(it.hasNext()) { Track t = it.next(); String artist = t.getArtist(); if(artist.equals(artistToRemove)) { it.remove(); } }

Use the Iterator’s remove method.

Page 66: 4 gouping object

66

Review

• Loop statements allow a block of statements to be repeated.

• The for-each loop allows iteration over a whole collection.

• The while loop allows the repetition to be controlled by a boolean expression.

• All collection classes provide special Iterator objects that provide sequential access to a whole collection.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 67: 4 gouping object

Grouping objects

Arrays

Page 68: 4 gouping object

68

What is an Array?

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 69: 4 gouping object

69

The size of an array is fixed

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 70: 4 gouping object

70

Arrays in Java

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 71: 4 gouping object

71

Declaring Arrays

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 72: 4 gouping object

72

Constructing Arrays

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 73: 4 gouping object

73

The length variable for 1D Arrays

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 74: 4 gouping object

74

The length variable for 2D Arrays

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 75: 4 gouping object

75

Example

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 76: 4 gouping object

76

Array Initializer

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 77: 4 gouping object

77

Enhanced for Statement

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 78: 4 gouping object

78

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 79: 4 gouping object

79

Enhanced forStatement

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 80: 4 gouping object

80

Fixed-size collections

• Sometimes the maximum collection size can be pre-determined.

• A special fixed-size collection type is available: an array.

• Unlike the flexible List collections, arrays can store object references or primitive-type values.

• Arrays use a special syntax.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 81: 4 gouping object

81

Creating an array object

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader; public LogAnalyzer() { hourCounts = new int[24]; reader = new LogfileReader(); } ... }

Array object creation — specifies size

Array variable declaration — does not contain size

Page 82: 4 gouping object

82

The hourCounts array

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 83: 4 gouping object

83

Using an array

• Square-bracket notation is used to access an array element: hourCounts[...]

• Elements are used like ordinary variables. • The target of an assignment:

hourCounts[hour] = ...;

• In an expression: hourCounts[hour]++; adjusted = hourCounts[hour] – 3;

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Page 84: 4 gouping object

84

Standard array use

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private int[] hourCounts; private String[] names; ... hourCounts = new int[24]; ... hourcounts[i] = 0; hourcounts[i]++; System.out.println(hourcounts[i]);

declaration

creation

use

Page 85: 4 gouping object

85

Array literals

• Array literals in this form can only be used in declarations.

• Related uses require new:

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private int[] numbers = { 3, 15, 4, 5 };

declaration, creation and initialization

numbers = new int[] { 3, 15, 4, 5 };

• The size is inferred from the data.

Page 86: 4 gouping object

86

Array length

• NB: length is a field rather than a method!

• It cannot be changed – ‘fixed size’.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private int[] numbers = { 3, 15, 4, 5 }; int n = numbers.length;

no brackets!

Page 87: 4 gouping object

87

Review • Arrays are appropriate where a fixed-

size collection is required. • Arrays use a special syntax. • For loops are used when an index

variable is required. • For loops offer an alternative to

while loops when the number of repetitions is known.

• Used with a regular step size (Increment by the same number each time).

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling


Recommended