grouping objects - university of texas at...

35
1 Grouping objects Introduction to collections 4.0 2 CSE1325: Object-Oriented Programming in Java 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.

Upload: others

Post on 06-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

1

Grouping objects

Introduction to collections

4.0

2 CSE1325: Object-Oriented Programming in Java

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 2: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

2

3 CSE1325: Object-Oriented Programming in Java

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.

4 CSE1325: Object-Oriented Programming in Java

Class libraries

•  Collections of useful classes. •  We don’t have to write everything

from scratch. •  Java calls its libraries, packages. •  Grouping objects is a recurring

requirement. –  The java.util package contains

classes for doing this.

Page 3: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

3

5 CSE1325: Object-Oriented Programming in Java

import java.util.ArrayList;

/** * ... */ public class Notebook { // Storage for an arbitrary number of notes. private ArrayList<String> notes;

/** * Perform any initialization required for the * notebook. */ public Notebook() { notes = new ArrayList<String>(); }

... }

6 CSE1325: Object-Oriented Programming in Java

Collections

•  We specify: –  the type of collection: ArrayList –  the type of objects it will contain: <String>

•  We say, “ArrayList of String”.

Page 4: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

4

7 CSE1325: Object-Oriented Programming in Java

Object structures with collections

8 CSE1325: Object-Oriented Programming in Java

Adding a third note

Page 5: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

5

9 CSE1325: Object-Oriented Programming in Java

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?

10 CSE1325: Object-Oriented Programming in Java

Using the collection public class Notebook { private ArrayList<String> notes; ...

public void storeNote(String note) { notes.add(note); }

public int numberOfNotes() { return notes.size(); }

... }

Adding a new note

Returning the number of notes (delegation)

Page 6: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

6

11 CSE1325: Object-Oriented Programming in Java

Index numbering

12 CSE1325: Object-Oriented Programming in Java

Retrieving an object

Index validity checks

Retrieve and print the note

public void showNote(int noteNumber) { if(noteNumber < 0) { // This is not a valid note number. } else if(noteNumber < numberOfNotes()) { System.out.println(notes.get(noteNumber)); } else { // This is not a valid note number. } }

Page 7: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

7

13 CSE1325: Object-Oriented Programming in Java

Removal may affect numbering

14 CSE1325: Object-Oriented Programming in Java

Generic classes

•  Collections are known as parameterized or generic types.

•  ArrayList implements list functionality: –  add, get, size, etc.

•  The type parameter says what we want a list of: –  ArrayList<Person> –  ArrayList<TicketMachine> –  etc.

Page 8: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

8

15 CSE1325: Object-Oriented Programming in Java

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.

16 CSE1325: Object-Oriented Programming in Java

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.

Page 9: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

9

Grouping objects

Collections and the for-each loop

18 CSE1325: Object-Oriented Programming in Java

Interlude: Some popular errors...

Page 10: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

10

19 CSE1325: Object-Oriented Programming in Java

/** * Print out notebook info (number of entries). */ public void showStatus(){ if(isEmpty = true) { System.out.println(“Notebook is empty”); } else { System.out.print(“Notebook holds “); System.out.println(notes.size() + “ notes); }}

There is a boolean field called ‘isEmpty’... What’s wrong here?

20 CSE1325: Object-Oriented Programming in Java

/** * Print out notebook info (number of entries). */ public void showStatus(){ if(isEmpty == true) { System.out.println(“Notebook is empty”); } else { System.out.print(“Notebook holds “); System.out.println(notes.size() + “ notes); }}

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

Page 11: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

11

21 CSE1325: Object-Oriented Programming in Java

/** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note){ if(notes.size() == 100) notes.save(); // starting new notebook notes = new ArrayList<String>();

notes.add(note);}

What’s wrong here?

22 CSE1325: Object-Oriented Programming in Java

/** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note){ if(notes.size == 100) notes.save();

// starting new notebook notes = new ArrayList<String>();

notes.add(note);}

This is the same.

Page 12: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

12

23 CSE1325: Object-Oriented Programming in Java

/** * Store a new note in the notebook. If the * notebook is full, save it and start a new one. */ public void addNote(String note){ if(notes.size == 100) { notes.save(); // starting new notebook notes = new ArrayList<String>(); }

notes.add(note);}

The correct version

24 CSE1325: Object-Oriented Programming in Java

Iteration

•  We often want to perform some actions an arbitrary number of times. –  E.g., print all the notes in the notebook. 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.

Page 13: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

13

25 CSE1325: Object-Oriented Programming in Java

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.

26 CSE1325: Object-Oriented Programming in Java

For-each loop pseudo code

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 14: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

14

27 CSE1325: Object-Oriented Programming in Java

A Java example

/** * List all notes in the notebook. */ public void listNotes() { for(String note : notes) { System.out.println(note); } }

for each note in notes, print out note

28 CSE1325: Object-Oriented Programming in Java

Review

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

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

Page 15: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

15

Grouping objects

The while loop

30 CSE1325: Object-Oriented Programming in Java

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 can use a boolean condition to decide whether or not to keep going.

•  A while loop provides this control.

Page 16: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

16

31 CSE1325: Object-Oriented Programming in Java

While loop pseudo code

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

32 CSE1325: Object-Oriented Programming in Java

/** * List all notes in the notebook. */ public void listNotes() { int index = 0; while(index < notes.size()) { System.out.println(notes.get(index)); index++; } }

A Java example

Increment index by 1

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

Page 17: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

17

33 CSE1325: Object-Oriented Programming in Java

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.

34 CSE1325: Object-Oriented Programming in Java

While without a collection

// Print all even numbers from 0 to 30. int index = 0; while(index <= 30) { System.out.println(index); index = index + 2; }

Page 18: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

18

35 CSE1325: Object-Oriented Programming in Java

Searching a collection

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

Grouping objects

Identity vs equality

Page 19: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

19

37 CSE1325: Object-Oriented Programming in Java

Side note: String equality

if(input == "bye") {

... }

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

...

}

Strings should always be compared with .equals

tests identity

tests equality

38 CSE1325: Object-Oriented Programming in Java

Identity vs equality 1 Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Jill”

:Person

Page 20: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

20

39 CSE1325: Object-Oriented Programming in Java

Identity vs equality 2 Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

40 CSE1325: Object-Oriented Programming in Java

Identity vs equality 3 Other (non-String) objects:

person1 == person2 ?

“Fred”

:Person

person1 person2

“Fred”

:Person

Page 21: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

21

41 CSE1325: Object-Oriented Programming in Java

Identity vs equality (Strings)

"bye"

:String

input

"bye"

:String

String input = reader.getInput();

if(input == "bye") {

...

}

== ?

➠ (may be) false!

== tests identity

42 CSE1325: Object-Oriented Programming in Java

Identity vs equality (Strings)

"bye"

:String

input

"bye"

:String

String input = reader.getInput();

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

...

}

equals ?

➠ true!

equals tests equality

Page 22: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

22

Grouping objects

Identity vs equality

44 CSE1325: Object-Oriented Programming in Java

:Element

myList:List

:Element :Element

:Iterator

myList.iterator()

:Element

Page 23: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

23

45 CSE1325: Object-Oriented Programming in Java

:Element :Element :Element

:Iterator

hasNext()? ✔ next()

Element e = iterator.next();

:Element

:Iterator

myList:List

46 CSE1325: Object-Oriented Programming in Java

:Element :Element :Element

hasNext()? ✔ next()

:Element

:Iterator :Iterator

myList:List

Page 24: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

24

47 CSE1325: Object-Oriented Programming in Java

:Element :Element :Element

hasNext()? ✔ next()

:Element

:Iterator :Iterator

myList:List

48 CSE1325: Object-Oriented Programming in Java

:Element :Element :Element

hasNext()? ✔ next()

:Element

:Iterator :Iterator

myList:List

Page 25: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

25

49 CSE1325: Object-Oriented Programming in Java

:Element :Element :Element

hasNext()? ✗

:Element

:Iterator

myList:List

50 CSE1325: Object-Oriented Programming in Java

Using an Iterator object

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 listNotes() { Iterator<String> it = notes.iterator(); while(it.hasNext()) { System.out.println(it.next()); } }

Page 26: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

26

51 CSE1325: Object-Oriented Programming in Java

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. •  Use if we might want to stop part way through. •  Often used with collections where indexed access is

not very efficient, or impossible.

•  Iteration is an important programming pattern.

52 CSE1325: Object-Oriented Programming in Java

The auction project

•  The auction project provides further illustration of collections and iteration.

•  One further point to follow up: the null value. –  Used to indicate, 'no object'. –  We can test if an object variable holds

the null variable.

Page 27: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

27

53 CSE1325: Object-Oriented Programming in Java

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.

Grouping objects

Arrays

Page 28: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

28

55 CSE1325: Object-Oriented Programming in Java

Fixed-size collections

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

•  Programming languages usually offer a special fixed-size collection type: an array.

•  Java arrays can store objects or primitive-type values.

•  Arrays use a special syntax.

56 CSE1325: Object-Oriented Programming in Java

The weblog-analyzer project

•  Web server records details of each access.

•  Supports webmaster’s tasks. –  Most popular pages. –  Busiest periods. –  How much data is being delivered. –  Broken references.

•  Analyze accesses by hour.

Page 29: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

29

57 CSE1325: Object-Oriented Programming in Java

Creating an array object

public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader;

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

Array object creation

Array variable declaration

58 CSE1325: Object-Oriented Programming in Java

The hourCounts array

Page 30: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

30

59 CSE1325: Object-Oriented Programming in Java

Using an array

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

•  Elements are used like ordinary variables. –  On the left of an assignment:

hourCounts[hour] = ...;

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

60 CSE1325: Object-Oriented Programming in Java

Standard array use private int[] hourCounts; private String[] names;

...

hourCounts = new int[24];

...

hourcounts[i] = 0; hourcounts[i]++; System.out.println(hourcounts[i]);

declaration

creation

use

Page 31: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

31

61 CSE1325: Object-Oriented Programming in Java

Array literals

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

System.out.println(numbers[i]);

•  Array literals can only be used in initialisations.

declaration and initialisation

62 CSE1325: Object-Oriented Programming in Java

Array length

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

int n = numbers.length;

•  Note: ‘length’ is not a method!!

no brackets!

Page 32: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

32

63 CSE1325: Object-Oriented Programming in Java

The for loop

•  There are two variations of the for loop, for-each and for.

•  The for loop is often used to iterate a fixed number of times.

•  Often used with a variable that changes a fixed amount on each iteration.

64 CSE1325: Object-Oriented Programming in Java

For loop pseudo-code

for(initialization; condition; post-body action) { statements to be repeated }

General form of a for loop

Equivalent in while-loop form

initialization; while(condition) { statements to be repeated post-body action }

Page 33: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

33

65 CSE1325: Object-Oriented Programming in Java

A Java example

for(int hour = 0; hour < hourCounts.length; hour++) { System.out.println(hour + ": " + hourCounts[hour]); }

int hour = 0; while(hour < hourCounts.length) { System.out.println(hour + ": " + hourCounts[hour]); hour++; }

for loop version

while loop version

66 CSE1325: Object-Oriented Programming in Java

Practice

•  Given an array of numbers, print out all the numbers in the array, using a for loop.

int[] numbers = { 4, 1, 22, 9, 14, 3, 9};

for ...

Page 34: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

34

67 CSE1325: Object-Oriented Programming in Java

Practice

•  Fill an array with the Fibonacci sequence.

int[] fib = new int[100];

fib[0] = 0; fib[1] = 1;

for ...

0 1 1 2 3 5 8 13 21 34 ...

68 CSE1325: Object-Oriented Programming in Java

for loop with bigger step

// Print multiples of 3 that are below 40.

for(int num = 3; num < 40; num = num + 3) {

System.out.println(num);

}

Page 35: Grouping objects - University of Texas at Arlingtoncrystal.uta.edu/~ylei/cse1325/data/Chapter04.pdf · 2010-06-16 · Grouping objects The while loop CSE1325: Object-Oriented Programming

35

69 CSE1325: Object-Oriented Programming in Java

Review

•  Arrays are appropriate where a fixed-size collection is required.

•  Arrays use special syntax. •  For loops offer an alternative to

while loops when the number of repetitions is known.

•  For loops are used when an index variable is required.