CSC248
Jun-Oct 2013
CHAPTER TWO
LIST ADT (Pn Yusnita Sokman)
List
2
Is a finite, ordered sequence of data items call
elements
Each list element has the same data type
(homogenous)
The basic operation for list is based on the
application of the problem
Example:
A
list of students, a list of available room, a list of cities
and a list of books
2
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
Cont
3
Normally consists of:
Retrieve
R i
an element
l
ffrom a lilist
Insert a new element to a list
Delete an element from a list
Find how many elements are in a list
Find whether an element is in a list
Find whether a list is empty
List Implementation
4
There two ways to implement a list:
Use
U
an array to store the
h elements
l
Array
Use
List
a linked structure
Linked
Prepared by: Pn Yusnita Sokman
List
CSC248
Jun-Oct 2013
List Implementation
5
When we define for sequential list, the using of
arra is ssuitable
array
itable to implement the list
Element in the list is homogenous
The size of element always change depend on
insertion and deletion element in the list
First element in the list called head/front
Last element in the list called tail/rear
List Implementation
6
Figure:
a0
a1
a2
a3
a4
an
a[0]
a[1]
a[2]
a[3]
a[4]
a[n]
head
tail
To create new list, determine empty list and traverse
the list,, it is q
quite easy:
y
Create
new list
Need
to define an array variable type
Need variables to count the element in the list
6
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
List Implementation
7
Empty
list
Need
to test the variables that count the number of element
in the list. If the value is zero empty list
Traverse
Can
list
be done using for statement
For insertion and deletion operation it is quite
difficult
d
cu depend
depe d on
o types
ypes of
o list
s
List Implementation
8
Consider a list with a sorting element
Insertion
I
i
and
dd
deletion
l i operation
i must maintain
i i the
h
characteristics after completed the process
To insert new element
Need
to shift on the right for every element in the list in
order to give a place to anew element
To
delete element
Need
to shift on the left for every element from the list in
order to replace the element that we want to delete
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
List Implementation
9
Insert 19 into list
12
15
12
17
15
21
24
35
40
44
17
19
21
24
35
40
44
44
Delete 35 from list
12
15
17
21
24
35
40
12
15
17
21
24
40
44
The efficiency for insertion and deletion operation of list is depending on
1. the number of shifted element
2. the number of element in the list
9
The List Interface
10
The Java collection frameworks Arraylist class
implements the List interface with underlying
nderl ing array
arra
that allows constant-time access of any element
from the index
The List interface extends the Collection interface
with methods that have an index as either
parameter
t or a return
t
type
t
10
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
The List ADT
11
Description
A list is a linear collection that supports indexing of its
elements.
The list is mutable, unordered, has no fixed limit on size, and
allows duplicates.
The list element type is unspecified
Attribute
size: the number of elements in the list,
list the range of
occupied positions is 0 to size 1
head: the first element of the list
tail: the last element of the list
11
The List ADT
12
Properties
Empty
list
size
is 0
head and tail reference null(a special value indicating they
dont reference a list position)
Nonempty
List
List
list
has one element
size is 1; head and tail refer to the same position
has more than one element
size is the number of elements in the list; head refers to the first
element, tail refer to the last element, and these elements are in
different positions
12
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
The List ADT
13
Properties
All
elements
l
in
i the
h list
li must b
be iin adjacent
dj
positions.
ii
The index of the first position is 0 and the index of the
last position is size 1; every indexed position refers to
a list element.
13
The List ADT
14
Operations/methods
E get
t (i
(int
t index);
i d )
Pre-condition: 0 <= index < size
Responsibilities: returns the elements stored at the given
index position
Post-condition: the list is unchanged
Returns: element at position index
14
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
The List ADT
15
Operations/methods
E set
t (i
(int
t index,
i d
E element);
l
t)
Pre-condition: 0 <= index < size
Responsibilities: replace the element at position index with
new element (E)
Post-condition: the element previously at index is replaced
by new element (E); size, head and tail are unchanged
Returns: the element that had previously been at position
index
15
The List ADT
16
Operations/methods
int
i
t indexOf
i d Of (Object
(Obj t element);
l
t)
Pre-condition: none
Responsibilities: determine index of the first occurrence of
target in the list
Post-condition: list is unchanged
Returns: the index of the first occurrence of target in the list
if found, or 1 if not found
16
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
The List ADT
17
Operations/methods
void add (int index,
index E element);
Pre-condition: 0 <= index < size
Responsibilities: insert element into the list at the specified location
Post-condition:
element is inserted in the list at position index
size is incremented by 1
head references the new element only if the list was previously
empty, otherwise head is unchanged
tail references the element in the first position if the list was
previously empty, otherwise tail s position is advanced by 1
Returns: nothing
17
The List ADT
18
Operations/methods
E remove (i
(int
t index);
i d )
Pre-condition: 0 <= index < size
Responsibilities: remove element at position index
Post-condition:
Element at position index is removed from the list
size is decremented by 1
head refers to null if the list is now empty, else refer to the
element in the first position
tail position is decremented by 1; tail is null if the list is empty
Returns:
the element removed
18
Prepared by: Pn Yusnita Sokman
CSC248
Jun-Oct 2013
The ArrayList Class
19
The ArrayList class implements the List interface
A ArrayList
An
A
object can be thought off as an
improved version of the one-dimensional array
Random
access of an element from its index:
public
E get (int index);
public E set (int index, E element);
19
The ArrayList Class
20
Insertion
or removal of an element at a given index:
public
void add (int index,
index E element);
public E remove (int index);
An
ArrayList objects size is automatically maintained
during the execution of program(automatic resizing)
public
void add (int index, E element);
public boolean add (E element);
//insert at back
20
Prepared by: Pn Yusnita Sokman
10
CSC248
Jun-Oct 2013
The ArrayList Class
21
relative position of each element in an ArrayList
object is given by an index :
The
an
integer range from 0 to n -1, where n represents the
number of elements in the ArrayList object
ArrayList
object is possible to store both integer &
string elements in the same ArrayList object
Eg
g
Suzi,
S
i
1234
Ali,
Ali
6543
Khai,
Kh
i
9876
21
Methods Specifications
22
Initializes this ArrayList object to be empty, with the
specified initial capacity
capacit
public ArrayList object (int initialCapacity);
Create
an empty ArrayList object called fruits with an
initial capacity of 100
ArrayList fruits = new ArrayList (100);
//create an empty ArrayList object of size 100
ArrayList fruits = new ArrayList ();
//default constructorcreate an empty ArrayList
//object(default initial capacity, 10)
22
Prepared by: Pn Yusnita Sokman
11
CSC248
Jun-Oct 2013
Methods Specifications
23
Append the specified element to the end of this
Arra List object.
ArrayList
object The average
a erage Time(n) is constant.
constant
public boolean add(E element);
Insert items at the end of an ArrayList object:
fruits.add (apples);
[0]
[1]
[2]
[0]
[1]
[2]
apples
oranges
apples
fruits add (
fruits.add
(oranges);
oranges );
fruits.add (durian);
[0]
[1]
[2]
apples
oranges
durian
23
Methods Specifications
24
Insert items into the list at the specified location
public
bli void
id
fruits.add
fruits.add
fruits.add
fruits.add
fruits.add
add
dd (i
(int
t index,
i d
E element);
l
t)
("apples");
("oranges");
("durian");
("apples");
(2,"cherries");
[0]
[1]
[2]
[3]
[4]
apples
oranges
cherries
durian
apples
24
Prepared by: Pn Yusnita Sokman
12
CSC248
Jun-Oct 2013
Methods Specifications
25
Determine the number of elements in this ArrayList
object
public int size();
Suppose we create an arrayList object as follow:
fruits.add
fruits.add
fruits.add
f it
fruits.add
dd
("apples");
("oranges");
("durian");
("
("apples");
l ")
Then;
System.out.println (fruits.size());
//will output 4
25
Methods Specifications
26
Returns the element at the specified index
public
bli E get
t (i
(int
t index);
i d )
Example:
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add (
("apples");
apples );
System.out.println (fruits.get(2));
So,
would return durian
26
Prepared by: Pn Yusnita Sokman
13
CSC248
Jun-Oct 2013
Methods Specifications
27
Replaces the element at the specified index in this
ArrayList object with the specified element
public E set (int index, E element);
Example:
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add ("apples");
System.out.println (fruits.set(2, "bananas"));
Will change the element at index 2 to bananas and output
durian, the element that had been at index 2 before the set
method was invoked.
27
Methods Specifications
28
Searches for the first occurrence of specified element,
testing
g for equality
q
y with the equal
q method.
public int indexOf (object element);
Example:
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add ("apples");
System.out.println (fruits.indexOf("durian"));
// will output 2
System.out.println (fruits.indexOf("kiwi"));
// will output 1
28
Prepared by: Pn Yusnita Sokman
14
CSC248
Jun-Oct 2013
Methods Specifications
29
Removes the element at the specified index in this ArrayList object.
All elements that were at positions > the specified index have been
moved to the next lower position.
position
public E remove (int index);
Example:
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add ("apples");
System out println (fruits.remove(2));
System.out.println
(fruits remove(2));
The output will be durian, and fruits will now contain
apples, oranges and apples
29
EXERCISES
Prepared by: Pn Yusnita Sokman
15
CSC248
Jun-Oct 2013
Exercise 1
31
Write a Java program segment for the following
processes:
Create 2 array lists named aList and sList.
Insert the following numbers and store them into aList .
12
78
90
Replace element at location 3 with 100
Remove all numbers that can be divided by 3 from aList
and store them into sList.
Display the contents of the aList and sList.
Display the size of the aList and sList.
Calculate and display the sum of numbers in sList
31
Solution 1
32
ArrayList aList = new ArrayList();
A
ArrayList
Li t sList
Li t = new A
ArrayList();
Li t()
Prepared by: Pn Yusnita Sokman
16
CSC248
Jun-Oct 2013
Solution 2
33
aList.add("12");
aList.add("78");
Li t dd("78")
aList.add("1");
aList.add("7");
aList.add("90");
Solution 2
34
int data;
f (i t i = 0;
for(int
0 i<5;
i 5 i++)
i )
{
data=Integer.parseInt(JOptionPane.s
howInputDialog("Input number: "));
aList.add(data);
}
Prepared by: Pn Yusnita Sokman
17
CSC248
Jun-Oct 2013
Solution 3
aList.set(3, "100");
35
Solution 4
for(int i=0;i<aList.size();i++)
{
Object n =aList.get(i);
int num=Integer.parseInt(n.toString());
if(num%3==0)
{
sList.add(num);
aList.remove(i);
i--;
}
}
36
Prepared by: Pn Yusnita Sokman
18
CSC248
Jun-Oct 2013
Solution 5
System.out.println("\n// Data in aList");
for(int i=0;i<aList.size();i++)
{
System.out.println(aList.get(i));
}
System.out.println("\n// Data in sList");
for(int i=0;i<sList.size();i++)
{
System.out.println(sList.get(i));
}
37
Solution 6
System.out.println("The size of the
aList is " + aList.size());
aList size());
System.out.println("The size of the
sList is " + sList2.size());
38
Prepared by: Pn Yusnita Sokman
19
CSC248
Jun-Oct 2013
Solution 7
int sum = 0;
for(int
(
i=0;i<sList.size();i++)
()
)
{
Object n =sList.get(i);
int num=Integer.parseInt(n.toString());
sum = sum + num;
}
System.out.println("Sum
y
p
(
of numbers in
sList: " + sum);
39
Exercise 2
40
Determine output for the following statement:
class ArrayListTracing {
public static void main(String
p
(
g args[])
g []) {
ArrayList trace = new ArrayList();
System.out.println("Initial size of trace: " + trace.size());
trace.add("T");
trace.add("E");
trace.add("T");
trace.add("O");
trace.add("N");
trace.add("E");
trace.add(2, "S");
System.out.println("Size of trace after additions: "
+ trace.size());
System.out.println("Contents of trace: " + trace);
trace.remove( E );
trace.remove("E");
trace.remove(1);
System.out.println("Size of trace after deletions: "
+ trace.size());
System.out.println("Contents of trace: " + trace);
}
}
Prepared by: Pn Yusnita Sokman
20
CSC248
Jun-Oct 2013
Exercise 3
41
Write a Java application that performs the following
tasks:
Declaring an array list called floatList.
Inserting FOUR (4) floating point numbers into floatList at
the front.
Inserting a floating point number, say 7.5 in between
location 2 and 3 of floatList.
Printing the elements of floatList
Removing the second element of floatList and print the
output.
Calculate and display the sum of numbers in floatList
Exercise 2
42
Given the following Invoice ADT:
public class Invoice
{
private
private
private
private
private
public
public
public
public
public
public
public
int orderID;
String custName;
String prodName;
int prodQuantity;
double unitPrice;
Invoice(int oid, String cn, String pn, int pq, double up) {}
int getOrderID() {}
String getCustName() {
{}
}
String getProdName() {}
int getProdQuantity(){}
double getUnitPrice(){}
String toString() {}
Prepared by: Pn Yusnita Sokman
21
CSC248
Jun-Oct 2013
Continue
43
Write a Java application to solve the following
problems:
Input 10 invoices into a sequential list named Invoice.
Calculate the total payment of all invoices. The payment is
calculated by multiplying proqQuantity and unitPrice.
Display the information of invoice that makes the highest
payment.
Count the number of invoices where the payment is more
than RM5000, and also display the information of those
invoices.
Prepared by: Pn Yusnita Sokman
22