L08Arrays - Mathematical & Computer Sciences

advertisement
F21SF
Software Engineering Foundations
L8 - Arrays 2
arrays – pros and cons, ArrayList
Dept of
Computer
Science
13/04/2015
Monica Farrow EM G30
email : M.Farrow@hw.ac.uk
Material available on Vision
Arrays 2
1
Topics

More about arrays


Pros and cons
ArrayList class
13/04/2015
Arrays 2
2
Arrays (summary)



An array in java is a special kind of object, with a unique
syntax
An array is a fixed-length sequence of values of the same
type
Arrays are good for:



Fixed length sequences
Finding or altering elements according to their index position
An array is a kind of list. Lists are good for:


Holding elements in order (ideally order of adding)
Processing each element in turn, by traversing the list
13/04/2015
Arrays 2
3
Problems with arrays


An array is created with a fixed size.
If our list is variable in size,



We need to make sure that there is room to add items
We need to keep a note of how many items are in the array,
and alter it if the number of items changes
Deleting items from the middle of the array is timeconsuming

All the elements which come after the deleted item should
be shuffled down, one by one
numItems = 6
index
13/04/2015
numItems = 5
1
3
0
9
8
3
0
1
2
3
4
5
index
6
Arrays 2
1
3
0
8
3
0
1
2
3
4
5
6
4
Arrays contd

If order is important, adding and maintaining
order is time-consuimng


Using arrays involves the programmer in writing a
block of code for manipulations such as




All the elements which will come after the inserted
element have to shuffled up, one by one (starting
at the end)
Deleting an item
Sorting the array
Searching the array for a value
There are standard algorithms for these blocks,
but careful coding and testing is still necessary.
13/04/2015
Arrays 2
5
ArrayList

The ArrayList class in the Java Collections Framework
stores items in an array and provides methods for adding,
removing and getting



You can use reliable methods for these operations
The size of the array is automatically enlarged if necessary
There is a size() method so you don’t have to keep
updating the number of items you have.
13/04/2015
Arrays 2
6
import statement





Up till now, the java classes that we have used have been in the
package java.lang which is always automatically included in a
program
To use classes in a different package, we have to include an import
statement at the start of the class file.
The import statement includes the name of the package and the
name of the classes imported
Some people just import all the classes in the package
 Only one import statement per package
 It’s not obvious which classes are imported from where
 E.g. import java.util.*;
Other people just import the classes needed
 E.g. import java.util.ArrayList;
13/04/2015
Arrays 2
7
Generic types


Earlier versions of java did not allow the programmer to
specify the content type of an ArrayList . Generic
types, new in java 5, are an improvement.
<..> encloses the class of objects to be stored in the
collection
private ArrayList <Student> studentList;



Checks at compile time that classes match
Whatever goes into this ArrayList must be a Student.
Whatever comes out will be a Student.
13/04/2015
Arrays 2
8
Keeping a collection of student details



We would like to keep details of a group of students
 Using the Student class from the previous lecture
This example demonstrates using an ArrayList of objects,
and making a frequency report (counting!)
We often have a separate class which maintains the list of
objects, and provides methods such as
 These methods return information that we can find
using ArrayList methods



Find how many items in the list
Find the nth item
These methods return information needed by our
particular program


Searching for a particular entry in the list
Counting, summing, etc
13/04/2015
Arrays 2
9
A manager class


Typically a program will have
 Classes for distinct objects e.g. Student, Car etc
 Classes for collections of similar objects e.g. StudentList
 A ‘manager’ or ‘interface’ class which handles the main functions
of the program, often interacting through a GUI or text interface.
So far our programs have no interaction – just writing to standard
output.
 A main method alone in a class to start the manager or interface
class.
Today we introduce a ‘manager’ class which handles the top-level
functions. For the Student application, this involves setting up a list of
students, calling some of the StudentList methods, and producing
output to Standard output
13/04/2015
Arrays 2
10
Class Diagram
Main
main(arg[] : String) : void
StudentList
studentList : ArrayList <Student>
StudentManager
allStudents : StudentList
StudentManager()
run() : void
StudentList()
populate() : void
getSize() : int
getAtIndex(index:int) : Student
Various methods traversing the list
and returning details
Name
Student
Instance variables and methods
as before
Instance variables and methods
as before
13/04/2015
Arrays 2
11
Keeping a collection of student details

The StudentList class starts:
import java.util.ArrayList;
//demonstrates using an ArrayList
public class StudentList {
private ArrayList<Student> studentList;
//create an empty arraylist
public StudentList() {
studentList = new ArrayList<Student> ();
}
13/04/2015
Arrays 2
12
Adding in student details

Done in the populate() method, discussed later

At the moment, pretend that we have put in details of
student objects into the list.
13/04/2015
Arrays 2
13
Traversing the ArrayList

There is a special ‘for-each’ loop for collections such as
ArrayList
for (Object-type object-name :
collection-name)

For each item in the collection, perform the loop body,
referring to the object as object-name
//for each Student object (refer to as s)
//in studentList
for (Student s : studentList){
//do something with s
}
13/04/2015
Arrays 2
14
The getTableOfStudents method

It is better to have a method which returns a String rather than one
that prints to System.out. In this way, the value which is returned can
be written to standard output (today), to a text file, or displayed in a
GUI (both, later in the course)
public String getTableOfStudents()
{
String report = "ID NAME
YEAR
QUALIFICATIONS";
for (Student s : studentList){
report += String.format("%-6s", s.getId());
report += String.format("%-15s",
s.getName().getFullName() );
report += String.format("%-4d", s.getYear());
report += "\n";
}
return report;
}
13/04/2015
Arrays 2
15
Getting input from the user

This code uses the method
JOptionPane.showInputDialog which returns the
user input as a String
String id = JOptionPane.showInputDialog(null,
"Enter id");

To use this method, you also need an import statement




import javax.swing.JOptionPane;
More details about JOptionPane when we discuss GUIs
If you want integer input, you would have to convert it
An example of this is shown in the FileI/O and Exceptions
lecture

int idnum = Integer.parseInt(id);
13/04/2015
Arrays 2
16
Searching the list


This code gets an id from the user, and uses a method in
the StudentList class, findById() to find the student with
the id given in the parameter.
It assumes that the student will be found.
String id = JOptionPane.showInputDialog(null, "Enter id");
Student s = allStudents.findById(id);
String firstName = s.getName().getFirstName();
System.out.println("The person with id " + id
+ " is called " + firstName);
13/04/2015
Arrays 2
17
Searching the list - findById

This method in the StudentList class searches the
ArrayList of Student objects (studentList) for an
entry with id which matches that given in the parameter.
 Returns the object if found, null otherwise
 Methods returning positive integers usually return -1 if
not found
public Student findById(String id)
{
for (Student s : studentList)
if (s.getId().equals(id))
return s;
return null;
}
13/04/2015
Arrays 2
18
If id not found in list

The run method in StudentManager checks to see if the
returned object is null or not, and gives the user 3
chances to enter a correct one.
while (not found && count <3)
get id and search for it
inc count of tries
if object returned
get name and print it
change found to true
else
if count < 3 print ‘Try again’
13/04/2015
Arrays 2
19
The populate method


The populate method creates some people and adds them into the
list
In a real system, this information would probably come from a
database or text file
//populate the array list
public void populate() {
String [] quals1 = {"MIC", "ARA" };
Student s1 = new Student ("0011",
new Name("Helen Scott"), quals1, 1);
this.addOneStudent(s1); //method in same class
etc...
13/04/2015
Arrays 2
20
Adding to the list



This method uses the ArrayList add method to
provide Student objects to be added to the list
It doesn’t add it if there is already a Student object in the
list with the same id.
It is quite common for methods to return true or false, to
let the user know that they worked (next slide)
public boolean addOneStudent(Student s) {
String id = s.getId();
Student inList = this.findById(id);
if (inList == null) {
studentList.add(s); //ArrayList add method
return true;
}
return false;
}
13/04/2015
Arrays 2
21
Method purpose

Often methods do one of two things:

return a value which can be used later in the program


Perform an action, and do not return a value (void)


E.g. getModel(), estimateDistance() etc
E.g. System.out.println(), setModel(“Ka”)
The addOneStudent does both

It performs the add, and lets us know whether it has
worked
13/04/2015
Arrays 2
22
Checking the add

We can then check the return value and see whether the
add worked or not
boolean ok = this.addOneStudent(s6);
if (!ok) {
System.out.println("Duplicate entry "
+ s6.getId());
}

But we can also choose to ignore the fact that the method
returns a value. The populate() method shows both.
this.addOneStudent(s6);
13/04/2015
Arrays 2
23
A frequency array




There is a method in the StudentList class which returns
how many students are in each year.
First, find what the highest year is.
Then, declare an array of integers, each element
represents the number of students in the corresponding
year. Years go 1,2,3,4 etc. Indexes go 0,1,2, etc
Traverse list of students. For each student, find their year,
and add 1 to the count with the index position ‘year-1’
Frequency = the count of
the number students in
the corresponding year
Index positions
year
13/04/2015
6 3 2
0 1 2
1
1 2 3
Maxyear
Arrays 2
Maxyear -1
24
Frequency count
int maxYear = getMaxYear();
//work out how many people at each year
int [] freqYears = new int [maxYear];
for (Student s : studentList) {
int y = s.getYear();
freqYears[y-1]++;
}
//create a report
String report = "NUMBER OF STUDENTS IN EACH YEAR\n";
for (int i = 0; i < freqYears.length; i++) {
report += "Year " + (i+1) + " : " + freqYears[i] +
"\n";
}
13/04/2015
Arrays 2
25
The StudentList class continued


Examine the rest of the code in your own time.
In particular, notice differences between having integers
in a java array, and objects in an ArrayList class



Using ArrayList methods such as add, get, size
Get the object from the array, then use the object’s
methods
Special for-each loop for ArrayLists
13/04/2015
Arrays 2
26
Why Arrays

Arrays



Some programming languages only provide arrays as a form
of list
Fast for accessing elements directly
Slow for adding and deleting elements if we want to keep
the list in a sorted order

There are lots of alternative ways of storing lists

More about all this in Advanced Software Engineering
13/04/2015
Arrays 2
27
To Do Now


Read over lecture and example code.
A class with an ArrayList of objects is used in the
remainder of the examples in this course
13/04/2015
Arrays 2
28
Download