Some of the
advantages
ArrayList
has over arrays are
it can grow dynamically.
It provides more powerful insertion and search mechanisms than arrays.
Let's take a look at using an
ArrayList
that contains
Strings
:
List<String> myList = new ArrayList<String>();
In many ways,
ArrayList
is similar to a String
[] in that it declares a
container that can hold only String
s, but it's more powerful than a String[]
. Let's
look at some of the capabilities that an ArrayList
has through the following program:
ArrayList
import java.util.*;
class Array_List
{
public static void main(String arg[])
{
ArrayList<String> list = new ArrayList<String>();
list.add("Merit");
list.add("Campus");
list.add("Java");
System.out.println(list.size()); // LINE A
list.remove("Campus"); // LINE B
System.out.println(list.contains("Java")); // LINE C
System.out.println(list.get(1)); // LINE D
Iterator<String> iterate = list.iterator();
while(iterate.hasNext())
{
System.out.println(iterate.next());
}
}
}
DESCRIPTIONCommonly used method of the ArrayList
class is add
(). It adds the specified element to the end of the list. size
() returns the number of elements present in the invoking list. In the above program, we added three strings to myList and then invoked size
() which returned 3 as can be seen in the first line of output. We can also remove elements from a list using remove
() which is depicted in LINE B
. In order to check whether an element is present in a list or not contains
method is used. LINE C
explains the same. We can also retrieve an element at a specified position using get(int index)
. This is shown in LINE D
where the element at position 1 is retrieved. This method returns true
if the list contains the specified element, else false
. To traverse the elements in a list, Iterator
class can be used. An object of this class is created when iterator
() is invoked and using this the list is traversed.
THINGS TO TRY
- How to insert an element at a specified position in a list?
( Use add(int index , E element)
where index is the position at which you want to insert the element)
- There are many other methods like
set(int index , E new_element)
to replace element at position index with new_element), isEmpty
() to check if a list contains any elements or not, clear
() to remove all the elements of a list etc. Try to get accustomed to these methods too.