#### Transcript Collections

```Random, Collections & Loops
Chapter 5
Conditionals and Loops
• So far, we’ve looked at:
– making decisions with if
– how to compare data
– Boolean expressions
• Today we’ll look at:
– Generating lists of random numbers
– Storing lists (collections) of objects
– repeat processing steps in a loop
RANDOM
The Random Class
• The Random class is part of the java.util
package
• It provides methods that generate pseudorandom
numbers
• A Random object performs complicated calculations
based on a seed value to produce a stream of
seemingly random values
//********************************************************************
// RandomNumbers.java
Author: Lewis/Loftus
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//********************************************************************
import java.util.Random;
public class RandomNumbers
{
//----------------------------------------------------------------// Generates random numbers in various ranges.
//----------------------------------------------------------------public static void main (String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
continued
continued
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);
}
}
Sample Run
A random integer: 672981683
From 0 to 9: 0
From 1 to 10: 3
From 20 to 34: 30
From -10 to 9: -4
A random float (between 0-1): 0.18538326
From 1 to 6: 3
Examples – code to outcome
Given a Random object named gen, what range of
values are produced by the following
expressions?
gen.nextInt(25)
Range?
0 to 24
gen.nextInt(6) + 1
1 to 6
gen.nextInt(100) + 10
10 to 109
gen.nextInt(50) + 100
100 to 149
gen.nextInt(10) – 5
-5 to 4
gen.nextInt(22) + 12
12 to 33
Examples – outcome to code
Write an expression that produces a random
integer in the following ranges:
Range
0 to 12
gen.nextInt(13)
1 to 20
gen.nextInt(20) + 1
15 to 20
gen.nextInt(6) + 15
-10 to 0
gen.nextInt(11) – 10
COLLECTIONS & LOOPS
Grouping (i.e., collecting) objects
• Many applications involve collections of objects:
– Personal organizers.
– Library catalogs.
– Student-record system.
• The number of items to be stored varies.
– Items deleted.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Example: 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.
Consider a Notebook project.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
import java.util.ArrayList;
/**
* ...
*/
public class Notebook the type of collection
{
// Storage for an arbitrary number of notes.
private ArrayList<String> notes;
the type of objects
/**
in the collection
* Perform any initialization required for the
* notebook.
*/
public Notebook()
{
notes = new ArrayList<String>();
}
...
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Object structures with collections
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Features of the collection
• It increases its capacity as necessary.
• It keeps a private count (size() method).
• 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
Using the collection
public class Notebook
{
private ArrayList<String> notes;
...
public void storeNote(String note)
{
}
public int numberOfNotes()
{
return notes.size();
}
Returning the number
of notes (delegation)
...
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Index numbering
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Retrieving an object
Index validity checks
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.
}
}
Retrieve and print the note
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Removal may affect numbering
notes.remove(1);
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
Removal may affect numbering
notes.remove(1);
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes,
Michael Kölling
For-each Loops
• Simplifies repetitive processing of items in a collection
• For example, suppose bookList is an ArrayList<Book> object:
ArrayList<Book> bookList = new ArrayList<Book>();
• The following loop will print each book:
for (Book myBook : bookList)
System.out.println (myBook);
Logic of a for-each loop
Are there more items
in the collection?
true
Statements to
process each item
false
Quick Check
Write a for-each loop that prints all of the Student
objects in an ArrayList<Student> object called
roster.
for (Student student : roster)
System.out.println (student);
Other Collection Types
• List (e.g., java.util.ArrayList)
– Ordered elements
– Allows duplicates
• Set (e.g., java.util.HashSet)
– Unordered elements
– No duplicates
• Map (e.g. java.util.HashMap)
– Unordered elements, stored as key-value pairs
– No duplicate keys (can be duplicate values)