0% found this document useful (0 votes)
11 views40 pages

CHAPTER 2 - ARRAY LIST (New)

Chapter Two discusses the List Abstract Data Type (ADT), describing it as an ordered collection that can hold various types of objects and can be implemented using either an ArrayList or a Linked List. It compares arrays with ArrayLists, highlighting the dynamic nature of ArrayLists and their ability to handle object references. The chapter also outlines the operations associated with lists, such as retrieval, insertion, and deletion, and details the methods provided by the ArrayList class in Java.

Uploaded by

aravin1107
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views40 pages

CHAPTER 2 - ARRAY LIST (New)

Chapter Two discusses the List Abstract Data Type (ADT), describing it as an ordered collection that can hold various types of objects and can be implemented using either an ArrayList or a Linked List. It compares arrays with ArrayLists, highlighting the dynamic nature of ArrayLists and their ability to handle object references. The chapter also outlines the operations associated with lists, such as retrieval, insertion, and deletion, and details the methods provided by the ArrayList class in Java.

Uploaded by

aravin1107
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

CHAPTER TWO

LIST ADT
List
2

• A list is an ordered collection (sometimes called


sequence). It is a sequential data structure.
• A List is like an array but it allows you to add as
many elements as you like.
• The elements of a list can be any type of objects not
a primitive data type.
• There are two types of list :
– Sequential List (ArrayList)
– Linked List

2
Comparison between array and ArrayList

◼ ArrayList is an improved version of one-dimensional array.

Array ArrayList

Fixed Length (static data structure) Variable length - size starts from zero, grows when you add
element and shrink when you remove element (dynamic data
structure)
Elements of specific data type Holds a collection of object references

If the data has a known number of elements or small fixed size when there will be a large variation in the amount of data that you
upper bound, or where efficiency in using primitive types is want to put into an array.
important
Can hold primitive data and object types it holds only object types and not primitive types (eg, int).

Characteristics : Characteristics :
• the size of the array must be given by the time the program is • The size of the array can be given at compile time or at runtime,
compiled so the application can begin execution and wait until it has a better
• The memory allocated for the array is permanently bound to idea of its space needed before allocating the array.
the array variable name • The memory that is allocated is not permanently bound to the
• The size of the array is fixed for the duration of the program array variable. It is perfectly legal to assign a different block of
so the array cannot shrink or grow to meet the user’s needs. memory to array variable.
• The size of the block that is allocated is fixed, but it is possible to
allocated a new block of memory that is smaller or larger than the
original block
List
4

◻ 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

4
Cont…
5

◻ Normally consists of:


� Retrieve an element from a list
� 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
6

◻ There two ways to implement a list:


� Use an array to store the elements
■ Array List
� Use a linked structure
■ Linked List
List Implementation
7

◻ When we define for sequential list, the using of


array is suitable 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

7
List Implementation
8

◻ 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 quite easy:
� Create new list
■ Need to define an array variable type
■ Need variables to count the element in the list

8
List Implementation
9

� Empty list
■ Need to test the variables that count the number of
element in the list. If the value is zero – empty list
� Traverse list
■ Can be done using for statement
◻ For insertion and deletion operation it is quite
difficult depend on types of list

9
List Implementation
10

◻ Consider a list with a sorting element


� Insertion and deletion operation must maintain the
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

10
List Implementation
11
Insert 19 into list
12 15 17 21 24 35 40 44

12 15 17 19 21 24 35 40 44

Delete 35 from list

12 15 17 21 24 35 40 44

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

11
The List Interface
12

◻ The Java collection framework’s Arraylist class


implements the List interface with underlying
array 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 or a return type

12
The List ADT
13

◻ 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, the range of
occupied positions is 0 to size –1
� head: the first element of the list
� tail: the last element of the list

13
The List ADT
14

◻ Properties
� Empty list
■ size is 0
■ head and tail reference null(a special value indicating they
don’t reference a list position)
� Nonempty list
■ List has one element
■ size is 1; head and tail refer to the same position
■ List 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

14
The List ADT
15

◻ Properties
� All elements in the list must be in adjacent positions.
� 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.

15
The List ADT
16

◻ Operations/methods
� E get (int index);
■ 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

16
The List ADT
17

◻ Operations/methods
� E set (int index, E element);
■ 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

17
The List ADT
18

◻ Operations/methods
� int indexOf (Object element);
■ 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

18
The List ADT
19

◻ Operations/methods
� void add (int 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

19
The List ADT
20

◻ Operations/methods
� E remove (int index);
■ 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

20
The ArrayList Class
21

◻ The ArrayList class – implements the List interface


◻ An ArrayList object can be thought of 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);

21
The ArrayList Class
22

� Insertion or removal of an element at a given index:


■ public void add (int index, E element);
■ public E remove (int index);
� An ArrayList object’s 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

22
The ArrayList Class
23

� The relative position of each element in an ArrayList


object is given by an index :
■ 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 :
“Suzi”, “Ali”, “Khai”,
1234 6543 9876

23
Methods Specifications
24

◻ Initializes this ArrayList object to be empty, with


the specified initial capacity
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 constructor–create an empty ArrayList
//object

24
Methods Specifications
25

◻ Append the specified element to the end of this


ArrayList object. The average Time(n) is constant.
public boolean (add E element);
� Insert items at the end of an ArrayList object:
fruits.add (“apples”); [0] [1] [2]
apples

fruits.add (“oranges”); [0] [1] [2]


apples oranges

fruits.add (“durian”); [0] [1] [2]


apples oranges durian

25
Methods Specifications
26

◻ Insert items into the list at the specified location


public void add (int index, E element);
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add ("apples");
fruits.add (2,"cherries");

[0] [1] [2] [3] [4]


apples oranges cherries durian apples

26
Methods Specifications
27

◻ Determine the number of elements in this


ArrayList object
public int size();
� Suppose we create an arrayList object as follow:
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add ("apples");
� Then;
System.out.println (fruits.size());
//will output 4

27
Methods Specifications
28

◻ Returns the element at the specified index


public E get (int index);
� Example:
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add ("apples");
System.out.println (fruits.get(2));
� So, would return “durian”

28
Methods Specifications
29

◻ 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.

29
Methods Specifications
30

◻ Searches for the first occurrence of specified element,


testing for equality with the equal 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

30
Methods Specifications
31

◻ 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.
public E remove (int index);
◻ Example:
fruits.add ("apples");
fruits.add ("oranges");
fruits.add ("durian");
fruits.add ("apples");
System.out.println (fruits.remove(2));

◻ The output will be “durian”, and fruits will now contain


“apples”, “oranges” and “apples”

31
EXERCISES
Lets try this
33 Determine output for the following statement:
import java.util.ArrayList;
public class ArrayListProj {
public static void main(String[] args) {
E
String[] fruits = new String[4];
fruits[0] = "Mango"; x
fruits[1] = "Apple";
fruits[2] = "Strawberry"; e
fruits[3] = "Watermelon";
System.out.println(fruits);
r
ArrayList fruitList = new ArrayList();
fruitList.add("Mango"); c
fruitList.add("Apple");
fruitList.add("Strawberry");
fruitList.add("Watermelon");
i
fruitList.remove("Strawberry"); s
fruitList.clear();
System.out.println(fruitList.contains("Raspberry")); e
System.out.println(fruitList);
}
}

1
Lets
try
Determine output for the following statement:

import java.util.ArrayList;
34
this public class ArrayListProj {
public static void main(String[] args) {
String[] fruits = new String[4];
fruits[0] = "Mango";
E fruits[1] = "Apple";
fruits[2] = "Strawberry";

x
fruits[3] = "Watermelon";
System.out.println(fruits);

e ArrayList fruitList = new ArrayList();


fruitList.add("Mango");
fruitList.add("Apple");
r fruitList.add("Strawberry");
fruitList.add("Watermelon");
System.out.println(fruitList);
c fruitList.set(1,“Avocado");

i
System.out.println(fruitList);

fruitList.remove("Strawberry");

s System.out.println(fruitList);

System.out.println(fruitList.contains("Raspberry"));
e System.out.println(fruitList.contains("Avocado"));

fruitList.clear();
System.out.println(fruitList);
}
}
2
Lets try this
35 Determine output for the following statement:
import java.util.ArrayList;

public class Array3 {


E
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>(); x
names.add("Muhameed");
names.add("Essa"); e
names.add("Ali");
names.add("Hameed");
System.out.println(names);
r
names.add("Ahmed"); c
names.add("Usama");
System.out.println(names); i
names.remove(1);
System.out.println(names); s
System.out.println(names.get(2));
e
String name = names.get(0);
System.out.println(name);
System.out.println(names.indexOf("Ahmed"));

}
}
3
Exercise 4
36

◻ Determine output for the following statement:


class ArrayListTracing {
public static void main(String args[]) {
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(1);
System.out.println("Size of trace after deletions: " + trace.size());
System.out.println("Contents of trace: " + trace);
}
}
Exercise 5
37

◻ 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 1 7 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

37
Exercise 6
38

◻ 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 7
39

Given the following Invoice ADT:


public class Invoice
{
private int orderID;
private String custName;
private String prodName;
private int prodQuantity;
private double unitPrice;

public Invoice(int oid, String cn, String pn, int pq, double up) {…}
public int getOrderID() {…}
public String getCustName() {…}
public String getProdName() {…}
public int getProdQuantity(){…}
public double getUnitPrice(){…}
public String toString() {…}
}
Continue…
40

◻ 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.

You might also like