7.10 The ArrayList class
In addition to arrays, Java provides the class ArrayList to implement a list. Unlike an array, the size of a ArrayList object can grow and shrink during program execution. Therefore, you need not be concerned about the number of data elements. The elements of a ArrayList are references to Object. Using a ArrayList is slightly slower than using an array.
/**
* This program demonstrates an ArrayList
* and its methods
*/
import java.util.ArrayList; // Needed for ArrayList class
public class ArrayListDemo
{
public static void main(String[] args)
{
// Create an array list.
ArrayList<String> list = new ArrayList<>();
// Display the size of the array list.
System.out.println("Initial size of list: " + list.size());
// Add elements to the array list.
list.add("Sunday");
list.add("Tuesday");
list.add("Wednesday");
list.add("Thursday");
list.add("Friday");
list.add("Saturday");
// Now insert an item at index 1.
list.add(1, "Monday");
// Display the size of the array list.
System.out.println("Size of list after additions: "
+ list.size());
// Display the array list.
System.out.println("Contents of list: " + list);
// Remove elements from the array list.
list.remove("Saturday");
// Display the array list.
System.out.println("Contents of list: " + list);
// Now remove the item at index 2.
list.remove(2);
// Display the array list.
System.out.println("Contents of list: " + list);
}
}
Output :
Initial size of list: 0
Size of list after additions: 7
Contents of list: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
Contents of list: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday]
Contents of list: [Sunday, Monday, Wednesday, Thursday, Friday]
Size of list after additions: 7
Contents of list: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
Contents of list: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday]
Contents of list: [Sunday, Monday, Wednesday, Thursday, Friday]
ArrayList Objects and the foreach Loop
A foreach loop can be used to process the elements of a ArrayList object one at a time. For example, suppose list is an object of ArrayList class of String objects, The code for foreach loop will look like this :
for (String str : list) { //write code here }
Example
import java.util.ArrayList; // Needed for ArrayList class
/**
* This program demonstrates foreach loop.
*/
public class ForEachDemo
{
public static void main(String[] args)
{
// Create an ArrayList.
ArrayList<String> list = new ArrayList<>();
// Add some values to the ArrayList.
list.add("One");
list.add("Two");
list.add("Three");
for (String str : list)
{
System.out.println(str);
}
}
}
Output :
One
Two
Three
Two
Three
No comments:
Post a Comment