56
Modul 3 Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0

Modul 3

  • Upload
    leif

  • View
    39

  • Download
    0

Embed Size (px)

DESCRIPTION

Modul 3. Collections af objekter Arraylist Collections Objektorienteret design og Java. 4.0. Main concepts to be covered. Collections (especially ArrayList ). The requirement to group objects. Many applications involve collections of objects: Personal organizers. Library catalogs. - PowerPoint PPT Presentation

Citation preview

Page 1: Modul  3

Modul 3

Collections af objekter • Arraylist• CollectionsObjektorienteret design og Java.

4.0

Page 2: Modul  3

Main concepts to be covered

Collections(especially ArrayList)

Modul 3

Page 3: Modul  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.

Modul 3

Page 4: Modul  3

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.

Modul 3

Page 5: Modul  3

Modul 3 5

Take a quick look at notebook1

Explore the notebook1 project.

Page 6: Modul  3

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.

Modul 3

Page 7: Modul  3

Module 3

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>(); } ...}

Importing Class libraries

Page 8: Modul  3

Collections

We specify: the type of collection: ArrayListthe type of objects it will contain: <String>

We say, “ArrayList of String”.

Modul 3

Page 9: Modul  3

Object structures with collections

Modul 3

Page 10: Modul  3

Adding a third note

Modul 3

Page 11: Modul  3

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?

Modul 3

Page 12: Modul  3

Using the collection

Modul 3

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 13: Modul  3

Index numbering

Modul 3

Page 14: Modul  3

Retrieving an object

Modul 3

Index validity checkspublic 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. }}

Retrieve and print the note

Page 15: Modul  3

Removal may affect numbering

Modul 3

Page 16: Modul  3

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.

Modul 3

Page 17: Modul  3

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.

Modul 3

Page 18: Modul  3

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.

Modul 3

Page 19: Modul  3

Modul 3 19

Some Collections types

List Set SortedSet NavigableSet MapQueue

java.util.ArrayList java.util.LinkedList java.util.Vector java.util.Stack

java.util.EnumSet java.util.HashSet java.util.LinkedHashSet java.util.TreeSet

java.util.SortedSet

java.util.NavigableSet java.util.HashMap java.util.Hashtable java.util.EnumMap java.util.IdentityHashMap java.util.LinkedHashMap java.util.Properties java.util.TreeMap java.util.WeakHashMap

java.util.LinkedList java.util.PriorityQueue

Page 20: Modul  3

Grouping objectsCollections and the for-each loop

Page 21: Modul  3

Interlude:Some popular errors...

Modul 3

Først en kvik lille test

Page 22: Modul  3

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

Modul 3

What’s wrong here?

Page 23: Modul  3

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

Modul 3

This is the same as before!

Page 24: Modul  3

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

Modul 3

This is the same again

Page 25: Modul  3

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

Modul 3

and the same again…

Page 26: Modul  3

/** * 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); }}

Modul 3

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

Page 27: Modul  3

/** * 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); }}

Modul 3

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

Page 28: Modul  3

/** * 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);}

Modul 3

What’s wrong here?

Page 29: Modul  3

/** * 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);}

Modul 3

This is the same.

Page 30: Modul  3

/** * 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);}

Modul 3

The correct version

Page 31: Modul  3

Main concepts to be covered

CollectionsLoops: the for-each loop

Modul 3

Page 32: Modul  3

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.

Modul 3

Page 33: Modul  3

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.

Modul 3

Page 34: Modul  3

For-each loop pseudo code

Modul 3

for(ElementType element : collection) { loop body}

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

loop headerfor 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 35: Modul  3

A Java example

Modul 3

/** * 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

Page 36: Modul  3

Review

Loop statements allow a block of statements to be repeated.The for-each loop allows iteration over a whole collection.

Modul 3

Page 37: Modul  3

Grouping objectsThe while loop

Page 38: Modul  3

Main concepts to be covered

The while loop

Moduil 3

Page 39: Modul  3

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.

Modul 3

Page 40: Modul  3

While loop pseudo code

Modul 3

while(loop condition) { loop body}

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

boolean testwhile keyword

Statements to be repeated

Pseudo-code expression of the actions of a while loop

General form of a while loop

Page 41: Modul  3

A Java example

Modul 3

/** * List all notes in the notebook. */public void listNotes(){ int index = 0; while(index < notes.size()) { System.out.println(notes.get(index)); index++; }} 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 42: Modul  3

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.

Modul 3

Page 43: Modul  3

While without a collection

Modul 3

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

Page 44: Modul  3

Searching a collection

Modul 3

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.

Page 45: Modul  3

Grouping objectsIterators

Page 46: Modul  3

Main concepts to be covered

Iterators

Modul 3

Page 47: Modul  3

Modul 3

:Element

myList:List

:Element :Element

:Iterator

myList.iterator()

:Element

Page 48: Modul  3

Modul 3

:Element :Element :Element

:Iterator

hasNext()? ✔next()

Element e = iterator.next();

:Element

:Iterator

myList:List

Page 49: Modul  3

Modul 3

:Element :Element :Element

hasNext()? ✔next()

:Element

:Iterator :Iterator

myList:List

Page 50: Modul  3

Modul 3

:Element :Element :Element

hasNext()? ✔next()

:Element

:Iterator :Iterator

myList:List

Page 51: Modul  3

Modul 3

:Element :Element :Element

hasNext()? ✔next()

:Element

:Iterator :Iterator

myList:List

Page 52: Modul  3

Modul 3

:Element :Element :Element

hasNext()? ✗

:Element

:Iterator

myList:List

Page 53: Modul  3

Using an Iterator object

Modul 3

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 54: Modul  3

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.

Modul 3

Page 55: Modul  3

Exercises

On paper4.2, 4.3, 4.4, 4.5, 4.6, 4.10 and 4.11

Notebook 4.10 – 4.16

BankSolve Modul3Bank found under Opgaver/Modul3

ExtraExercisesOnLoops SportlExercise

Modul 3

Page 56: Modul  3

Exercise

On paper4.2, 4.3, 4.4, 4.5, 4.6 on page 93 to

Modul 3