The document discusses using collections like ArrayList in Java. It explains that collections allow storing an arbitrary number of objects and provide functionality to add, remove and iterate over items. The document also demonstrates how to use an ArrayList to organize music files by adding, getting and listing files. Iteration over collections using a for-each loop is described. Generic classes are introduced as a way to specify the type of objects a collection contains.
2. To learn how to use debugger to step the behavior of the program
To learn about object structures with collections – ArrayList.
To learn about ArrayList features and methods
To know what does generic classes mean
Iterations
2
3. The debugger is useful for gaining insights into program behavior
whether or not there is a program error.
The steps should follow in debugger:
◦ Set breakpoints.
◦ Examine variables.
◦ Step through code.
3
5. A collection of objects can store an arbitrary number of other
objects.
It is the notion of grouping things so that we can refer to them and
manage them all together.
A collection might be:
◦ large (all the students in a university)
◦ small (the courses one of the students is taking)
5
6. Many applications involve collection of objects:
Personal Organizer:
◦ Electronic calendars store event notes about appointments, meetings, birthdays, and
so on.
◦ New notes are added as future events are arranged, and old notes are deleted as
details of past events are no longer needed.
Library Catalogs:
◦ Libraries record details about the books and journals they own.
◦ The catalog changes as new books are bought and old ones are put into storage or
discarded.
Student Record System:
◦ Universities maintain records of students.
◦ Each academic year adds new records to the collection, while the records of those
who have left are moved to an archive collection.
◦ Listing subsets of the collection will be common: all the students taking Computing or
all the students due to graduate this year, for instance
6
7. Entries must be accessed efficiently
The number of items to be stored varies
◦ Need the ability to add and delete items
7
8. To understand this concept, we are going to write a class that can help
us organize our music files stored on a computer.
Our class won’t actually store the file details; instead, it will delegate
that responsibility to the standard ArrayList library class, which will save
us a lot of work.
Here are the basic operations we will have in the initial version of our
organizer:
◦ It allows tracks to be added to the collection.
◦ It has no predetermined limit on the number of tracks it can store, aside from
the memory limit of the machine on which it is run.
◦ It will tell us how many tracks are in the collection.
◦ It will list all the tracks.
We shall find that the ArrayList class makes it very easy to provide this
functionality from our own class.
8
9. Collections are known as parameterized or generic types.
Generic classes, in contrast to other classes we have seen so far, do not define
a single type in Java, but potentially many types.
ArrayList is a parameterized or generic type.
The ArrayList class, for example, can be used to specify an ArrayList of String,
an ArrayList of Person, an ArrayList of Rectangle, or an ArrayList of any other
class that we have available.
Each particular ArrayList is a separate type that can be used in declarations of
fields, parameters, and return values.
The type parameter says what we want a list of:
private ArrayList<Person> members;
private ArrayList<TicketMachine> machines;
9
10. Class libraries usually contain tried-and-tested collection classes.
We don’t have to write everything from scratch. Java calls its libraries,
packages.
◦ The java.util package contains classes for doing this.
10
12. An ArrayList is a dynamic data structure, meaning items can be
added and removed from the list.
Each item has an index.
Index values may change if items are removed (or further items
added).
We specify:
◦ the type of collection: ArrayList
◦ the type of objects it will contain: <String>
◦ private ArrayList<String> files;
We say, “ArrayList of String”.
12
13. The following figure illustrates how a MusicOrganizer object might
look with two filename strings stored in it; Object Structures with
Collection.
13
15. There are at least three important features of the ArrayList class that
you should observe:
◦ It is able to increase its internal capacity as required: as more items are
added, it simply makes enough room for them.
◦ It keeps its own private count of how many items it is currently storing.
Its size method returns that count.
size() accessor
It maintains the order of items you insert into it.
The add method stores each new item at the end of the list. You can
later retrieve them in the same order.
15
16. ArrayList implements list functionality (methods):
◦ add, get, remove, size, etc.
Once you have a new ArrayList objects, you can add elements to it
with the add method:
◦ listTest.add( "first item" );
◦ listTest.add( "second item" );
◦ listTest.add( "third item" );
◦ listTest.add( 7 );
16
17. Adding a new file
Returning the number of files
(delegation)
17
public class MusicOrganizer
{
private ArrayList<String> files;
...
public void addFile(String filename)
{
files.add(filename);
}
public int getNumberOfFiles()
{
return files.size();
}
...
}
18. Items in the list can be referenced by an Index number, and by using
the get method:
18
19. Index validity checkspublic 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?)
19
21. 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, …
21
22. 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
22
23. 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
23
24. We often want to repeat some actions over and over
◦ e.g. “do this action for each student in the university”
◦ e.g. “do this action seventeen times”
◦ e.g. “do this action until this condition is true”
Java loops provide us with a way to control how many times we
repeat these actions
With collections, we often want to repeat things once for every
object in a particular collection
24
25. 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
25
26. /**
* List all file names in the organizer.
*/
public void listAllFilesForEachLoop()
{
for(String filename : files) {
System.out.println(filename);
}
}
for each filename in files, print out filename
26
27. Statements can be nested, giving greater selectivity:
public void findFiles(String searchString)
{
for(String filename : files) {
if(filename.contains(searchString)) {
System.out.println(filename);
}
}
}
27
28. public String findFiles(String searchString)
{
for (String filename : files) {
if (filename.contains(searchString)) {
return filename; // return the first match if one is
found
}
}
return “”; //return empty string if NO match is found
}
28
29. Easy to write
Termination happens naturally
The collection cannot be changed
There is no index provided
◦ Not all collections are index-based
We can’t stop part way through
◦ Except when using a return statement
It provides ‘definite iteration’,
aka ‘bounded iteration’
29
30. The for-each loop is used whenever we need to perform some action
on every item in a collection:
view every one
change every one
check every one
select some or count some from every one
30
31. 1. Get first element of the collection files
2. Execute statement using that value
3. Get next element from the collection and repeat from 2
4. But if no elements left then stop
for (String filename : files) {
if (filename.contains(searchString)) {
System.out.println(filename);
}
}
31
32. We have seen how this results in structures of objects working
together to solve a common task.
Objects can create other objects, and they can invoke each other’s
methods. Understanding these object interactions is essential in
planning, implementing, and debugging applications.
We can use pen-and-paper diagrams, code reading, and debuggers
to investigate how an application executes or to track down bugs.
32
33. We have made good progress with the basics of organizing our
music collection. We can store the names of any number of music
files and even play them.
We have done this with relatively little coding effort, because we
have been able to piggyback on the functionality provided by library
classes: ArrayList from the standard Java library and a music player
that uses a third-party class library.
We have also been able to do this with relatively little knowledge of
the internal workings of these library classes; it was sufficient to
know the names, parameter types, and return types of the key
methods.
33
34. Barnes, David J., and Kölling, Michael. 2012. Objects First with
Java, A practical Introduction Using BlueJ (5th Edition). Boston:
Preston.
Liang, Y. Daniel. 2011. Introduction to Java Programming,
Comprehensive (8th Ed.) Prentice Hall.
http://www.tutorialspoint.com/java/java_decision_making.htm
http://www.homeandlearn.co.uk/java/java.html
34