You are on page 1of 20

CO4025

Introduction to
Computer Programming
Lecture 10
Array Lists
Introduction
 We’re going to look at ArrayList Objects
 These are dynamic containers available within
Java
 They are more flexible than arrays
 We’ll see how to manipulate them with a list of
integers
 We’ll expand the mechanism to deal with lists of
objects

CO4025 Introduction to Programming 2


ArrayList
 Java provides a number of container classes that enable
use to store data
 We’ve seen how to handle one-dimensional and two-
dimensional arrays
 We’re going to look at Java’s ArrayList class
 This behaves like a one-dimensional array but it’s
dynamic
 This means that we can expand or contract the array by
simply adding or removing elements
 The syntax is not the same as that for arrays

CO4025 Introduction to Programming 3


Handling a List of Integers
 We’re going to write a simple program to do the
following tasks:
 Create a list of integers
 Fill the list with random numbers
 Output the contents of the list
 We’ll also demonstrate the effects of some
ArrayList methods
 We’ll write a couple of methods to fill the list and
output it

CO4025 Introduction to Programming 4


Declaring an ArrayList Object
 We need to import the java.util. library to utilise
ArrayList objects
 Within main() we declare a new ArrayList object,
integerList:
ArrayList integerList = new ArrayList();
 We call a method, fillArrayList with integerList
and the number of elements that wish to add to the list as
arguments:
fillArrayList(integerList, 10);
 Then we pass the list to a method that outputs the contents:
printArrayList(integerList);

CO4025 Introduction to Programming 5


fillArrayList Method
 The fillArrayList method is called with an ArrayList and an integer
representing its size
 size controls the loop within which we assign a random number to successive
elements of the list
 We call the ArrayLists’s add method with two arguments:
 i – the current element of the list
 The random number that has been generated, which is stored at the location pointed to by i

private static void fillArrayList(ArrayList arrayIn, int size) {


Random rand = new Random(); //random number generator
int n = 10;
//assign random value 1 - n to each element of array
for(int i = 0; i < size; i++){
arrayIn.add(i, (1 + (Math.abs(rand.nextInt()) % n)));

}
}

CO4025 Introduction to Programming 6


printArrayList Method
 The printArrayList method is called with an ArrayList
 We call this object’s size() method to control the loop that iterates through
the list
 We output a label indicating which element we’re outputting
 We also call the list’s get() method with the controlling counter i as an
argument to retrieve the element currently pointed to
 All the information is printed to the screen

private static void printArrayList(ArrayList arrayIn) {


for(int i = 0; i < arrayIn.size(); i++){
System.out.println("integerList #" + i + "
contains " + arrayIn.get(i));
}
}

CO4025 Introduction to Programming 7


Program Output
 If we run the program we see that random numbers between 1 and
10 have been added to the list and output:
integerList #0 contains 7
integerList #1 contains 8
integerList #2 contains 10
integerList #3 contains 5
integerList #4 contains 4
integerList #5 contains 6
integerList #6 contains 5
integerList #7 contains 2
integerList #8 contains 10
integerList #9 contains 7

CO4025 Introduction to Programming 8


Manipulating the ArrayList:
set()
 ArrayList objects provide a number of
methods to manipulate the contents of the list
 The set() method takes two arguments:
 The index of the element position
 The value of the object that is to be placed at that
position in the list
 This replaces the existing value
 We can see the effect of the following call
because the existing numbers in the list are < 11
integerList.set(5,20);

CO4025 Introduction to Programming 9


Manipulating the ArrayList:
add()
 The add() method expands the list
 It takes two arguments:
 The index of the element position
 The value of the object that is to be placed at that
position in the list
 This inserts a new value into the list
 We can see the effect of the following call where
we expect the previous value at element 6 to be
pushed one element down the list
integerList.add(6,21);

CO4025 Introduction to Programming 10


Manipulating the ArrayList:
remove()
 The remove() method contracts the list
 There are two versions: each takes a single
argument:
 The index of the element position from which data are
to be removed
 A specific object to be removed from the list
 This deletes the selected object
 We remove the first element of the list
integerList.remove(0);

CO4025 Introduction to Programming 11


Calling set() and add()
integerList #0 contains 7  The original
integerList #1 contains 8 contents of element
integerList #2 contains 10 #5 was 6
integerList #3 contains 5
 When we call the
set() and add()
integerList #4 contains 4 methods we see
integerList #5 contains 20 that element #5 is
integerList #6 contains 21 replaced by 20
integerList #7 contains 5  We see that the
rest of the list has
integerList #8 contains 2 been moved down
integerList #9 contains 10 one place and
integerList #10 contains 7 element #6
contains 21

CO4025 Introduction to Programming 12


Calling remove()
integerList #0 contains 8  We call remove() with
integerList #1 contains 10 the first element of the
list and output the
integerList #2 contains 5 results
integerList #3 contains 4  We see that the initial
integerList #4 contains 20 value 7 has
disappeared
integerList #5 contains 21  And the list has
integerList #6 contains 5 contracted by one
integerList #7 contains 2 element
integerList #8 contains 10
integerList #9 contains 7

CO4025 Introduction to Programming 13


Handling an ArrayList of Objects
 We can use the same mechanism we’ve seen
so far to manipulate an ArrayList of objects
 We need to do a bit more work to handle the
individual attributes of objects
 We’ll use our Person class to illustrate
 Within main() we declare the list and call two
methods with it:
ArrayList personList = new ArrayList();
fillObjectArrayList(personList);
printObjectArrayList(personList);

CO4025 Introduction to Programming 14


Entering Object Data into the List
 Within the method we initialise a loop
 We give the user the option of quitting
 If they do we exit the loop
 Otherwise we create a Person object
 Then we elicit attribute data from the user and assign the
attributes:
 Name: call setName()
 Gender: call setGender()
 Date of birth
 Month of birth
 Year of birth
 Call setDOB() with these data
 Then we add the instantiated Person object to the ArrayList

CO4025 Introduction to Programming 15


Entering Object Data into the List
private static void fillObjectArrayList(ArrayList arrayIn) throws IOException {
String s = "";
do {
System.out.println("enter name... (q to quit) ");
s = userInput.readLine();
if(s.toLowerCase().equals("q"))
break;
Person p = new Person();
p.setName(s);
System.out.println("enter gender ");
s = userInput.readLine();
p.setGender(s);
System.out.println("enter date of birth ");
int date = Integer.parseInt(userInput.readLine());
System.out.println("enter month of birth ");
int month = Integer.parseInt(userInput.readLine());
System.out.println("enter year of birth ");
int year = Integer.parseInt(userInput.readLine());
p.setDOB(date, month, year);
arrayIn.add(p);
}while(! s.toLowerCase().equals("q"));
}

16
Outputting Object Data From the
List
 Within the method we create a new Person
object, p
 We step through each element of the list
 We retrieve the current object using the get()
method
 We cast the retrieved object to a Person object and
assign it to p
 Then we extract p’s attributes and output the details
with appropriate labels

CO4025 Introduction to Programming 17


Outputting Object Data From the
List

private static void printObjectArrayList(ArrayList arrayIn) {


Person p = new Person();
for(int i = 0; i < arrayIn.size(); i++){
p = (Person) arrayIn.get(i);
System.out.println("Person #" + i + "'s details:");
System.out.println("Name " + p.getName());
System.out.println("Gender " + p.getGender());
System.out.println("DOB " + p.getDateOfBirth() +
'/' + p.getMonthOfBirth()
+ '/' + p.getYearOfBirth());
System.out.println("Approximate age " + p.getAge());
}
}

CO4025 Introduction to Programming 18


Output
Person #0's details:
Name billy
Gender male
 We can see
DOB 12/12/1990 that three
Approximate age 17 objects have
Person #1's details: been placed on
Name jack the list
Gender male  Their contents
DOB 2/5/1989
Approximate age 18
have been
Person #2's details:
retrieved and
Name jill displayed
Gender female
DOB 7/4/2001
Approximate age 6
CO4025 Introduction to Programming 19
Conclusion
 We’ve look at dynamic ArrayList
objects available within Java
 We’ve seen their flexibility in manipulating
lists of integers and lists of objects
 Next, we’ll see how to store and retrieve
data from files

CO4025 Introduction to Programming 20

You might also like