FIT9131
Week 5
Programming Foundations FIT9131
Class libraries, collections, iteration
1
Week 5
FIT9131
Week 5
Lecture outline
• Using Library classes • Java Collections
•ArrayList • Generic classes
• Loops (Repetitions) •for-each loop •while loop •for loop
2
FIT9131
Week 5
Class libraries
Java has a library of pre-defined classes which the programmer can access.
The class library contains many useful classes which are tried, tested and ready to use.
Using a pre-defined class library, we don’t have to write everything from scratch.
Thousands of classes are available through the Java class library.
3
FIT9131
Week 5
Class libraries
4
Class libraries are a powerful feature of object- oriented programming. They allow programmers to use pre-defined classes in their code, hence reducing their efforts and improving efficiency.
In the Java class library, classes that belong together are grouped into “packages”.
FIT9131
Week 5
Reading class documentation
The Java standard library documentation shows details about all classes in the library.
This is called the Java API (Application Programming Interface) documentation.
The documentation is readable in a Web browser :
http://docs.oracle.com/javase/8/docs/api/
Provides an interface description for all library classes 5
FIT9131
Week 5
Using library classes
If you want to use an object of another class in a class declaration, then that other class must be accessible to the compiler.
So to use classes from the Java class library, they must be “imported” using an import statement.
• the import statement must be placed at the beginning of the code for a class, before the class declaration.
• the imported classes can then be used in the same way as any other user-defined classes from the current project.
6
FIT9131
Week 5
Importing classes and packages
Single classes may be imported, eg :
import java.util.ArrayList;
import java.util.Random;
Or, Whole packages can be imported, eg :
import java.util.*;
import java.lang.*;
Note that classes from the java.lang package are automatically included in any Java program, so the last import statement in the example above is really not necessary.
7
FIT9131
Week 5
Importing a class into a BlueJ project
8
To bring another class into an existing BlueJ project:
Select Edit from menu
Select Add Class from file … Browse to find the class you want Select the .java file with the class name
Or, you may manually import a class from the Java libraries using the import statement (as shown on the previous slides).
FIT9131
Week 5
Grouping objects
Often we want to group together a number of values or objects and treat them as a group.
• Many applications involve collections of objects, e.g.:
• Telephone directory entries • Library catalogs
• Student record system
• The number and type of items to be stored varies, but there are typically some common operations, e.g.:
• items can be added, deleted, edited, sorted, etc 9
FIT9131
Week 5
Implementing Object Grouping
• It is easy to store single objects in a program : we just create a variable to represent each object, eg: student, staff, tuteRoom, etc.
• So how can we implement a “group of objects”?
• let’s start by simply creating individual variables for each object, and give the variables similar names, eg : student1, student2, student3, etc.
• this will work, but do you see a problem with this approach?
10
FIT9131
Week 5
Better solution : implementing Object Grouping
• Problem : the implementation shown on the previous slide quickly becomes impractical for large groups. For instance, what if you wish to have a group of 30000 students? Or, what if we do not even know how many students we will need, until the program is actually run?
• So we need a better and more flexible technique than creating a variable for each individual item in a group – we want some way of “grouping” the objects.
11
FIT9131
Week 5
Using Java Class libraries to group objects
• As indicated previously, Java has its libraries organised into packages of related classes. These packages handles different areas of programming, eg. maths, file input/output, etc.
• Grouping objects is a common requirement in programming.
• the java.util package contains some special classes designed for grouping objects. These are often called “Collections”.
12
FIT9131
Week 5
Java Collection :
• We are going to learn about a very useful Java Collection Class called “ArrayList”.
• This is commonly used to store a “list” of objects, e.g. : a list of Student objects, a list of Date objects, a list of Prize objects, etc.
• The ArrayList class provides the common methods used to manipulate the objects (so you do not need to write them yourself).
ArrayList
13
FIT9131
Week 5
Example : An organizer for music files
Let’s examine the music-organizer-v1 project (Chapter04 from textbook).
Program Logic :
• “Track” files (e.g. “Gangnam Style.mp3”) may be added.
• there is no pre-defined limit to the number of files.
• it can tell how many file names are stored in the
collection.
• it can list individual file names, using an index.
14
FIT9131
Week 5
Using a typical “collection” class
import java.util.ArrayList;
/** * … */
public class MusicOrganizer {
// Storage for an arbitrary number of file names.
private ArrayList
/**
* Perform any initialization required for the * organizer.
*/
public MusicOrganizer() {
files = new ArrayList
…
(1) importing a collection class called “ArrayList”
15 }
(2) declaring an attribute, files, to be a “collection of Strings”.
(3) creating the actual collection, then assigning it to the attribute files. Note : files is an object – of type “ArrayList of Strings”.
FIT9131
Week 5
Declaring Vs Creating objects
16
Person student; …
This statement declares a variable (an object in this case) called “student”, to be of type (a class in this case) “Person”.
Important : we cannot use this object as yet, because no memory has been allocated to it.
student = new Person(“1234”, “David Smith”);
This statement uses the “new” operator to create a Person object, allocates memory for
it, and returns a reference to it. That reference is then assigned to the variable student. Now we can use the object via student.
FIT9131 Week 5
Declaring and Creating objects at the same time
Person student = new Person(“1234”, “David Smith”); student
It is a common practice to combine the previous 2 statements into one statement like this, to achieve the same effect. The final result is the same.
(a Person
object)
“1234”
“David Smith”
The above statement means : create a variable called student, Then assign to it a reference to a Person object (with ID “1234” and name “DavidSmith”).
17
FIT9131 Week 5
Examples : Using objects
student.display();
String loginId = student.getId() + student.getSurname();
18
Examples of using methods
After an object has been created, we can call methods from the object to perform some tasks, e.g. printing some values, returning a value, etc. Note the use of the “dot notation” :
objectName.methodName(…).
FIT9131
Week 5
Declaring Collections
Collections can store an arbitrary number of elements.
Each element is one single object.
When declaring a collection we need to specify:
• the type of collection: eg. ArrayList
• the type of objects it will contain: eg.
• E.g: private ArrayList
This statement means : the attribute named files is an
“ArrayList of Strings”. 19
FIT9131
Week 5
Generic classes
• Collections are known as parameterized or generic types.
• An ArrayList implements “list” functionality: •add, get, size, etc.
• The
• ArrayList
• ArrayList
Classes which require such a parameter are known as generic classes
20
FIT9131
Week 5
Creating an ArrayList object
• In versions of Java prior to version 7 : •files = new ArrayList
• Java 7 introduced the‘diamond notation’ : •files = new ArrayList<>();
• the type parameter can be inferred from the variable being assigned to
• more convenient to declare and use 21
FIT9131
Week 5
Object structures with collections
22
MusicOrganizer
object
For instance, a typical MusicOrganizer object may look like this. Note that this object contains an
ArrayList of 2 String objects (representing 2 songs)
String
object
String object
ArrayList
object
FIT9131 Week 5
Adding a third music file
23
FIT9131
Week 5
Features of the
An ArrayList can increase its capacity as necessary. It keeps a private count of its objects (accessed by the
size() method).
It keeps the objects in order – objects may be
retrieved in the same order they were inserted.
Details of how all this is done are hidden.
• Does this matter? Do we really need to know?
• Does not knowing how it works prevent us from using this collection?
ArrayList
collection
24
FIT9131
Week 5
Using the collection
public class MusicOrganizer {
private ArrayList
public void addFile(String filename) {
files.add(filename); }
public int getNumberOfFiles()
{
Adding a new file
Note : the add() and size() methods shown below come from the ArrayList class.
25
return files.size();
}
… }
Returning the number of files
FIT9131
Week 5
ArrayList
Index numbering
Each element in an ArrayList has an index,
which is used to refer to the element. For Java, the index starts at 0.
26
(index 0)
(index 1)
(index 2)
FIT9131
Week 5
Example : Retrieving an object
public void listFile(int index)
{
if(index >= 0 &&
index < files.size())
Index boundary checks
{
String filename = files.get(index); System.out.println(filename);
} else
27
System.out.println(“Error : invalid index”);
}
Retrieve and print the file name
Optional Error message
FIT9131 Week 5
Removal may affect numbering
(index 0)
(index 1)
(deleted)
28
FIT9131
Week 5
Review
Collections allow an arbitrary number of objects to be stored.
We have used the ArrayList class from the java.util package. In this collection:
• 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 parameterised or generic type. 29
FIT9131
Week 5
Programming Constructs
There are 3 main kinds of programming constructs :
1) Sequence
2) Selection
3) Repetition (or Iteration, or Looping)
We have already learnt constructs (1) and (2). We are learning (3) this week.
30
FIT9131
Week 5
Iteration (or loop, or repetition)
We often want to repeatedly perform some actions a number of times. For example:
• adding up a series of numbers
• calculating the final grade for each student
in a unit
Most programming languages include special
loop statements for this purpose.
Loops provide us with a way to perform these actions repeatedly and to control how many times we repeat those actions.
Looping is also called repetition or iteration. 31
FIT9131
Week 5
Iteration fundamentals
When dealing with collections, we often want to repeatedly perform some operation for every object in a particular collection.
- E.g. : printing out the names of all the student objects in a student database collection. Each “print” operation is identical for each student.
Java has several types of loop statements.
We will start with the Java for-each loop, which is design to be used with a Java Collection class.
32
FIT9131
Week 5
Syntax :
for
-
each
loop
General form of the for-each loop Loop header
for keyword
for (ElementType element : collection)
{
}
loop body
Statement(s) to be repeated
33
The above means : For each element (of type ElementType), in the given collection, perform the statement(s) in the loop body.
FIT9131
Week 5
A Java example
/**
* List all file names in the organizer. */
public void listAllFiles()
{
for (String filename : files)
System.out.println(filename);
}
34
In English, this “for-each loop” means :
for each filename in the collection of files, print out filename
FIT9131
Week 5
An alternative : the
while
loop
35
A for-each loop repeats the loop body for each object in the given collection.
Sometimes we require more variation than this. For example, we may want to read only part of a collection which satisfies certain conditions.
A while loop provides this control.
We typically use a boolean condition to decide whether or not to keep going with the while loop.
FIT9131
Week 5
Syntax :
while
loop
General form of a while loop boolean test
while keyword
while (loop condition)
{
}
Statements to be repeated
loop body
36
The above means : while the loop condition is true, perform the statements in the loop body.
FIT9131
Week 5
A Java while loop example
/**
* List all file names in the organizer.
*/
public void listAllFiles() {
Condition to be tested
int index = 0;
while (index < files.size()) {
37
}
}
String filename = files.get(index);
System.out.println(filename);
index++;
Increment index by 1 (What would happen if this step is omitted?)
Meaning : while the value of index is less than the size of the collection, get and print the next file name, and then increment index by 1
FIT9131
Week 5
Example : Searching a collection
int index = 0;
boolean found = false;
while(index < files.size() && !found) {
String file = files.get(index); if (file.contains(searchString))
// item found, stop searching!
found = true;
else
index++; }
// When we finish the loop, either we have found the
// item at position index, or we have finished searching // the whole collection and found no matching item.
38
FIT9131
Week 5
for
• for-each loop:
• easier to write. Works well with Java Collections. • safe : it is guaranteed to stop.
• whileloop:
• we don’t have to process the whole collection.
• doesn’t even have to be used with a collection.
• need to be careful : could be an infinite loop or try to process elements outside the collection.
39
-
each versus while
FIT9131
Week 5
Example : while loop without using a collection
// Print all even numbers from 2 to 30.
int index = 2;
while (index <= 30)
{
System.out.println(index);
index = index + 2; }
40
FIT9131 Week 5
An example: getting a menu choice
public int getMenuChoice()
{
int choice = 0;
Scanner input = new Scanner(System.in);
while (choice < 1 || choice > 4) // continues while choices are not valid {
System.out.println(“\n\nChoose one from the menu below”); System.out.println(“1 for Yes”);
System.out.println(“2 for No”);
System.out.println(“3 for Maybe”); System.out.println(“4 for Exit”);
choice = input.nextInt(); // accepts a user choice
if (choice < 1 || choice > 4) // rejects an invalid choice
System.out.println(“Choose a number between 1 and 4!!”);
}
return choice; // returns a valid choice }
41
FIT9131
Week 5
Review of loops
• 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 also provide special objects called Iterators that provide sequential access to a whole collection. We will learn these later.
42
FIT9131
Week 5
43
Choosing between a for a while loop
for-each loop:
• use this if we want to process every element.
while loop:
• use this if we might want to stop part way
through.
• use this for repetition that doesn’t involve a collection.
–
each and
FIT9131
Week 5
Another kind of loop: The
traditional
There are two variations of the for loop, for-each and a “normal” for.
The for loop is often used to iterate a fixed number of times – and not necessarily with a collection.
Often used with a variable that changes a fixed amount on each iteration.
for loops offer an alternative to while loops when the number of repetitions is known. For example with an array (more about this later) – a fixed sized collection.
for loops are used when an index variable is required. 44
for
loop
FIT9131 Week 5
for
loop syntax
General form of a for loop
for (initialization; condition; post-body action) {
statements to be repeated
}
The equivalent while-loop form
initialization; while (condition) {
statements to be repeated
post-body action
}
45
FIT9131 Week 5
A Java example : for versus while
for loop version
for (int number = 0; number < 100; number++) {
System.out.println(number);
}
int number = 0;
while (number < 100)
{
System.out.println(number);
number++;
}
while loop version
46
FIT9131
Week 5
loop with a bigger increment "step"
47
Example : for
Eg :
// Print multiples of 3 that are below 40.
for (int number = 3; number < 40; number = number + 3) {
}
System.out.println(number);
FIT9131
Week 5
Pre and post
The while and for-each and for loops are pre- test loops. Pre-test loops test the condition at the start of the loop. This means that the loop may or may not execute.
A post-test loop tests the condition at the end of the loop, so the loop is always executed at least once.
A post-test loop is usually used when you know that the loop has to be executed at least once.
Any one of the loop constructs can be used in any repetition situation, but there are times when one is more sensible than the others.
In Java, the post-test loop is a do ... while loop. 48
-
test loops
FIT9131 Week 5
Example : Adding numbers keyed in
public int addNumbers()
{
Scanner input = new Scanner(System.in);
int total = 0;
int number = 0;
do
{
System.out.println("Enter a number (-99 to stop):"); number = input.nextInt();
if (number != -99)
total = total + number; } while (number != -99);
return total;
}
49
FIT9131 Week 5
An equivalent pre
public int addNumbers()
{
Scanner input = new Scanner(System.in); int total = 0;
int number = 0;
while (number != -99)
{
System.out.println("Enter a number (-99 to stop):"); number = input.nextInt();
if (number != -99)
total = total + number;
}
return total;
}
50
-
test loop