import java.util.*;
/**
* AArrayList demonstrates various methods that can be
* implemented using the Java interface ArrayList.
*/
public class AArrayList {
public static void main(String[] args) {
// Creates a new List called arrayList.
List arrayList = new ArrayList();
// Adds Five fruit elements into arrayList and prints it.
arrayList.add("apples");
arrayList.add("bananas");
arrayList.add("grapes");
arrayList.add("pears");
arrayList.add("black plums");
System.out.println("My array list currently includes: "
+ arrayList);
System.out.println();
/**
* Adds the element 'watermelons' onto the list at
* index 0 (first element) and prints it.
* Keep in mind that computer function in binary,
* therefore all indices begin with 0.
*/
arrayList.add(0, "watermelons");
System.out.println("My array list now includes: "
+ arrayList);
System.out.println();
/**
* Adds the element 'oranges' onto the list at
* index 3 (fourth element) and prints it.
* Keep in mind that computer function in binary,
* therefore all indices begin with 0.
*/
arrayList.add(3, "oranges");
System.out.println("My array list now includes: "
+ arrayList);
System.out.println();
// Determines whether or not 'grapes' is in the arrayList.
System.out.println("'grapes' is an element in the list: "
+ arrayList.contains("grapes"));
System.out.println();
// Determines whether or not 'apricots' is in the arrayList.
System.out.println("'apricots' is an element in the list: "
+ arrayList.contains("apricots"));
System.out.println();
// Returns the element at index 2.
System.out.println("Element at index 2 is: " + arrayList.get(2));
System.out.println();
// Returns the element at index 1.
System.out.println("Element at index 1 is: " + arrayList.get(1));
System.out.println();
// Checks to see if arrayList is empty or not.
System.out.println("The array list is currently empty: "
+ arrayList.isEmpty());
System.out.println();
// Returns the current size of the array.
System.out.println("The size of our current array list is: "
+ arrayList.size());
System.out.println();
// Clears the entire array. (Removes all elements within it)
arrayList.clear();
// Checks to see if arrayList is empty or not.
System.out.println("The array list is currently empty: "
+ arrayList.isEmpty());
System.out.println();
}
}
-------------------------------------------------------------------------
OUTPUT:
My array list currently includes: [apples, bananas, grapes, pears, black plums]
My array list now includes: [watermelons, apples, bananas, grapes, pears, black plums]
My array list now includes: [watermelons, apples, bananas, oranges, grapes, pears, black plums]
'grapes' is an element in the list: true
'apricots' is an element in the list: false
Element at index 2 is: bananas
Element at index 1 is: apples
The array list is currently empty: false
The size of our current array list is: 7
The array list is currently empty: true
|