Arraylist: Based On Slides of Dr. Norazah Yusof
Arraylist: Based On Slides of Dr. Norazah Yusof
Lecture 17
Based on Slides of Dr. Norazah Yusof
object storage
Unlike an array, an ArrayList object:
Requires:
import java.util.ArrayList;
8-2
constructor
add method:
townList.add("Kangar");
townList.add("Alor Setar");
as follows:
townList.get(1); // 1 is the index of the item to get.
A loop is used in the following statement to access every
for(int i=0;i<townList.size();i++)
System.out.print(townList.get(i)+" ");
To remove items in an ArrayList, use the remove
method
townList.remove(1); //This statement removes the second item.
townList.remove("Penang"); //This statement removes the item
// with the value "Penang".
8-4
method:
townList.set(1, "Muar");
This statement replaces the value at index 1 with Muar
8-5
System.out.println(townList);
This statement yields :
[Muar, Alor Setar]
8-6
casts to work.
8-9
ArrayList Methods
add(Object o) add new object into ArrayList
get(int index) - retrieves object reference from
Exercises
Do Exercise 1:
Question
1, page 115
Question 2, page 116
Question 3, page 117
import java.util.ArrayList;
cList.add(new CircleArrayList(2.3));
cList.add(new CircleArrayList(3.3));
}
}