0% found this document useful (0 votes)
49 views29 pages

Topic 2-List (Sequential List) Arraylist Class: Edited by Miss Nafisah Amin

The document discusses lists and the ArrayList class in Java. It provides an overview of lists and their implementation in the Java Collection Framework. Key points include: Lists allow duplicate elements and store elements in sequence; The ArrayList and LinkedList classes implement the List interface; ArrayList is better than arrays because it is dynamically resizable and allows initialization without specifying a size. The document also covers common ArrayList methods like add, get, remove and compares ArrayList to arrays.

Uploaded by

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

Topic 2-List (Sequential List) Arraylist Class: Edited by Miss Nafisah Amin

The document discusses lists and the ArrayList class in Java. It provides an overview of lists and their implementation in the Java Collection Framework. Key points include: Lists allow duplicate elements and store elements in sequence; The ArrayList and LinkedList classes implement the List interface; ArrayList is better than arrays because it is dynamically resizable and allows initialization without specifying a size. The document also covers common ArrayList methods like add, get, remove and compares ArrayList to arrays.

Uploaded by

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

Topic 2- List (Sequential List)

ArrayList class
Edited by
Miss Nafisah Amin
Chapter Objective
Learn about lists interface
Learn a few method of ArrayList class
Explore how various operations, such as search, insert,
and remove, on lists are implemented
Comparison with an Array
Java Collection Framework
is a set of classes and interfaces that implement
commonly reusable collection data structures.
Part of Java Collection Framework hierarchy
dealing with the List interface;
interface
Collection

interface
List

AbstractList

ArrayList LinkedList
Introduction - List
 The Collection interface is the root interface for
manipulating collection objects.
 Java Collections Framework’s (JCF) List interface extends
the Collection interface by providing some index related
methods as either a parameter or a return type.
 List: A collection of elements of the same type
 Length of list is number of elements in list
 In any list objects, the elements are stored in sequence,
according to an index
 Lists are implemented in the JCF via the java.util.List
interface.
 It defines a list as essentially a more flexible version of an
array. Elements have a specific order, and duplicate
elements are allowed. Elements can be placed in a specific
position. They can also be searched for within the list.
 Two concrete classes implement List.
 ArrayList
 LinkedList
List Interface
Refer to interface List in java.util.List package
(http://docs.oracle.com/javase/6/docs/api/java/util/List.html)

The main methods in List Interface


# Method heading Discription
1 E get (int index); //Returns the elements at position index //in this List object

2 E set (int index, E //Replaces the element that was at //position index in this List object with //the parameter
element); element, and return //the previous occupant.

3 int indexOf (Object //Returns the index of the first //occurrence of element in this object, if //element appears in this
element); List object. //Otherwise, returns –1

4 void add (int index, E //Insert element at position index in this List //object; every element that was at a position //>=
element); index before this call is now at the next //higher position

5 E remove (int index); //Removes and return the element at //position index in this List object; every //element that
was at a position > //index before this call is now at the //next lower position

6 int size(); Returns the number of elements in a list


7 void clear(); Clear the list
8 boolean isEmpty(); Returns whether the list is empty or not
Continue…
Insertion or removal of an element at a given index:
public void add (int index, E element);
public E remove (int index);
Automatic resizing after
public void add (int index, E element);
public boolean add (E element); //insert at back
The ArrayList Class

 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
Eg :
[0] [1] [2] [3] [4]

“Suzi”, “Ali”, “Khai”


1234 6543 , 9876
ArrayList Constructors and Methods
Refer to ArrayList class from java.util
Method Description
Constructors :
public ArrayList(); Creates /intialize an array list
public ArrayList(int initialCapacity);
public ArrayList(Collection<? Extends E> c);

Adding Element :
public void add(E element); Insert object at the back of arraylist.
public void add(int index, E element); Insert object at position index and move the
elements up.
Replacing Element :
public E set(int index, E element); Set element at position index to object element

Getting the Element :


public E get(int index); Returns the object at position index.
public Object[] toArray(); Returns the values in array.
public <T>T[] toArray(T[] a); The array parameter can be any Object subclass
(eg, String). This returns values in that array (or a
larger array if necessary).
Method Description
Iterators:
public Iterator <E> iterator(); Returns an Iterator for forward traversal.
public ListIterator <E> listIterator(final int Returns a ListIterator for forward / backward /
modifying traversal, starting at index . Start from
end with a.listIterator(a.size()).
index); Returns a ListIterator for forward / backward /
modifying traversal.
public ListIterator<E> listIterator();

Searching:
public boolean contains(Object element); Returns true if ArrayList contains object.
public int indexOf(Object element); Returns index of first occurrence of object, or -1 if
not there.
public int lastIndexOf(Object element); Returns index of last occurrence of object, or -1 if
not there.
Removing Element :
public void clear(); removes all elements from ArrayList.
public boolean remove(int i); removes the element at position i.
removes the elements from positions I thru j
public boolean removeRange(int I, int j);

Other :
public int size(); Returns the number of elements in ArrayList.
Example
Exercise 1
1. Write Java program segments to create a
sequential lists named arrlist.
2. Write Java program segments to prompts user to
enter 10 integer numbers and store them into
arrlist .
2.1 Display the even number in the arrlist.
2.2 Remove the odd number from the arrlist.
2.3 Display all element in arrlist
Exercise 2
Given the following ArrayList ADT and Java application intList:

public class ArrayList


{
// declaration of other methods and data
public boolean add(Object elem)
{
// method definition to
// append data to the end of the list
}
public void add(int index, Object elem)
{
// method definition to
// insert element at the specified location
}
}
Exercise 2 Continue
import java.util.*; for(i=0;i<listnum.size()-1;i++) {
import javax.swing.*; for (j=1;j<listnum.size();j++){
public class intList
no1 =
{ Integer.parseInt((String)listnum.get(i));
public static void main(String [] args)
no2 =
{ Integer.parseInt((String)listnum.get(j));
final int SIZE = 7;
if ((no1 + no2)==0)
String strNum;
int number,i,j,no1,no2;
listnum.set(j,new String ("0"));
}
ArrayList listnum=new ArrayList(); }
for (i=0; i<SIZE; i++) //Loop2
{
strNum= JOptionPane.showMessageDialog(null,l
JOptionPane.showInputDialog("Input one istnum,"Output",JOptionPane.PLAIN_
integer number: "); MESSAGE);
listnum.add(i,strNum);
System.exit(0);
}
}}
//Loop1
Exercise 2 Continue
1. Trace and state the output for the above program if the
input are
-23, 32, 23, 5, 42, 15, -5. List the values of listNum at the
comment statement //loop1 and //Ioop2.
2 Write Java program segment to
1. Append EIGHT more numbers to listNum ranging from
-100 to 100 only.
2. Count and display positive and negative numbers in
listNum
ArrayList class Continue
The 8 methods discussed before, are just a
sampling (a few methods) of the ArrayList class’s
methods.
We can see that the ArrayList object is better
compared to the an array in many aspect.
ArrayList vs Array
Intialize
ArrayList Array
Initializes this ArrayList object to be When an array is constructed, the
empty, with the specified initial initial capacity MUST be specified.
capacity
Eg:
Create an empty ArrayList
object called fruits with an initial String [] vegetables = new String
capacity of 100 [10]; // makes vegetables an
 ArrayList fruits = new array object with null references at
ArrayList (100); // indexes 0 through 9.
create an empty
ArrayList object of size
100
 ArrayList fruits = new
ArrayList (); // default
constructor – create an
empty ArrayList object
ArrayList vs Array
ADD
ArrayList Array
Append the specified element to the To insert to an array, an index must
end of this ArrayList object be specified:
public boolean add (E element)
String [] vegetables = new String
Insert items at the end of an [10];
ArrayList object: vegetables [0] = “carrots”
ArrayList fruits = new ArrayList vegetables [1] = “broccoli”
(100); vegetables [2] = “spinach”
fruits.add (“apples”); vegetables [3] = “corn”
.
fruits.add (“oranges”);
fruits.add (“durian”);
fruits.add (“apples”);
The ArrayList object fruits will now
have: “apples”  index 0, “oranges”
 index 1, “durian”  index 2 and
“apples”  index 3
ArrayList vs Array
SIZE
ArrayList Array
Determine the number of elements in Array no size
this ArrayList object method
public int size()
Suppose we create an arrayList
object as follow:
ArrayList fruits = new ArrayList (100);
fruits.add (“apples”);
fruits.add (“oranges”);
fruits.add (“durian”);
fruits.add (“apples”);
Then;
System.out.println (fruits.size());
// will output 4
ArrayList vs Array
GET
ArrayList Array
Returns the element at the specified index •Array - index operator
public E get (int index) •Similar to “get” method for
Example: ArrayList
•However, index operator is better
ArrayList fruits = new ArrayList
because of the “overwritten”
(100);
capability
fruits.add (“apples”); Eg :
fruits.add (“oranges”); System.out.println (vegetables [1]);
fruits.add (“durian”); //would return “broccoli”
fruits.add (“apples”); •And that element can be overwritten
System.out.println (fruits.get(2)); Eg :
vegetables [1] = “potatoes”;
//So, would return “durian” •In contrast, the following is illegal if
fruits is an ArrayList object:
Eg : fruits.get (1) = “pears”;
// ILLEGAL
ArrayList vs Array
SET
ArrayList Array
Replaces the element at the specified An array’s index operator can be
index in this ArrayList object with the used on the left-hand side of an
specified element assignment statement.
public E set (int index, E element) Eg : vegetables [1] = “potatoes”;
Eg: // will change the element at index 1
to “potatoes”
ArrayList fruits = new ArrayList
(100);
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
ArrayList vs Array
IndexOF
ArrayList Array
Searches for the first occurance of An explicit search must be conducted
specified element, testing for equality Write own code(refer to page 204,
with the equal method. Collins)
public int indexOf (object element)
Eg.:
Eg:
ArrayList fruits = new ArrayList String [] vegetables = new String
(100); [10];
fruits.add (“apples”); Vegetables[0] = “carrots”;
fruits.add (“oranges”); Vegetables[1] = “broccoli”;
Vegetables[2] = “corn”;
fruits.add (“durian”); Vegetables[3] = “potatoes”;
fruits.add (“apples”); boolean found = false;
System.out.println
(fruits.indexOf(“apples”)); for(int j =0; j<6&& ! Found; j++)…..
// will output 1 If..equal..
System.out.println If(!found)..
(fruits.indexOf(“kiwi”));
// will output –1
ArrayList vs Array
REMOVE
ArrayList Array
Removes the element at the specified For removal anywhere in the array,
index in this ArrayList object. All must write own code (pg
elements that were at positions > the 203,Collins), to shift the data to the
specified index have been moved to the left. If not, the removed index will
next lower position. have no data.
public E remove (int index) Except for removing data at the end.
Eg:
ArrayList fruits = new ArrayList
(100);
fruits.add (“apples”);
fruits.add (“oranges”);
fruits.add (“durian”);
fruits.add (“apples”);
System.out.println
(fruits.remove(2));
/*The output will be “durian”, and
Good feature of Array;
Array vs ArrayList
# Array ArrayList
1 The index operator can be no big deal, ArrayList has the
used both for accessing “get” and “set” method for
and replacing elements in accessing and replacing.
an array. Eg:
Eg : fruits.set (j, fruits.get (j+1));
vegetables [j] =
vegetables [j +1];

2 An array can be initialized when the elements must be explicitly


it is constructed added :
Eg : Eg :
String [] vegetables = ArrayList fruits = new
{“corn”, ArrayList();
“broccoli”,”lettuce”}; fruits.add(“oranges”);
fruits.add(“bananas”);
Good feature of Array;
Array vs ArrayList continue
# Array ArrayList
3 You are allowed to store But, for the ArrayList object, you are
elements at any index in an allowed to store elements only at indices 0,
array. …..size().

4 You can create array of any But, or the ArrayList object, each element
type such as int. must be either of type Object or subclass of
Object.
ArrayList with an Object class
Example

Customer Class
Test Class
Exercise 3
 ArrayList object named staff that have 100 information
about staff. The information include; name, staff id, grade,
and address. Create the object (Staff) and insert into the
ArrayList;
Exercises
Reference
William J. Collins, Data Structures and the Java
Collections Framework, 2nd Edition, McGraw
Hill.
D.S Malik, P.S. Nair, Data Structure using Java,
2003, Course Technology.
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Ar
rayList.html

You might also like