Java - The ArrayList Class Tutorial
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
ArrayList has the constructors:
- ArrayList()
- ArrayList(Collection c)
- ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.
Apart from the methods inherited from its parent classes, ArrayList defines following methods:
- void add(int index, Object element): Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
- boolean add(Object o): Appends the specified element to the end of this list.
- boolean addAll(Collection c): Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.
- boolean addAll(int index, Collection c): Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
- void clear(): Removes all of the elements from this list.
- Object clone(): Returns a shallow copy of this ArrayList.
- boolean contains(Object o): Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
- void ensureCapacity(int minCapacity): Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
- Object get(int index): Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
- int indexOf(Object o): Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
- int lastIndexOf(Object o): Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
- Object remove(int index): Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >= size()).
- protected void removeRange(int fromIndex, int toIndex): Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.
- Object set(int index, Object element): Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
- int size(): Returns the number of elements in this list.
- Object[] toArray(): Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
- Object[] toArray(Object[] a): Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
- void trimToSize(): Trims the capacity of this ArrayList instance to be the list's current size.
void add(int index, Object element):
Insert the specified element at the specified position index in the list. If the index is not the specified index range i.e index < 0 || index > list.size(), then it throws IndexOutOfBoundsException. Suppose if we add an element using add() method, its add an element to the end of the list. using this method we can add the element at the specified location, the remaining elements in the list are adjusted with the new index numbers.
List list = new ArrayList();
list.add("Tom");
list.add("Smith");
list.add("Harley");
try {
list.add(5, "Clarke");
} catch (IndexOutOfBoundsException iex) {
iex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
In the above code I have a list with three elements(the list index start from 0), I am trying to add an element at index 5, it is throwing an IndexOutOfBoundsException. If I add an element within the range 0 - 3, it is not throw any Exceptions, it will add the element successfully to the list.list.add(3, "Clarke"); //end of the collection. [Tom, Smith, Harley, Clarke]
list.add(2, "Clarke"); //Added an element before the "Harley", [Tom, Smith, Clarke, Harley]
boolean addAll(int index, Collection c):
Inserts all of the elements in the specified collection into the list, starting at the specified position. It throws NullPointerException if the specified collection is null. It is also throws IndexOutOfBoundsException if the specified index in not in the range (index < 0 || index >= list.size() ). The add(Collection c) method adds the Collection to the end of the list.
List list = new ArrayList();
List list2 = new ArrayList();
list.add("Tom");
list.add("Smith");
list.add("Harley");
list2.add("Java");
list2.add("PHP");
list.addAll(3, list2);
System.out.println("List" + list);
List[Tom, Smith, Harley, Java, PHP]
boolean contains(Object o):
Returns true if this list contains the specified element. It returns true if and only if this list contains at least on element.
List list = new ArrayList();
list.add("Tom");
list.add("Smith");
list.add("Harley");
if (list.contains("Job")) {
System.out.println("The list contains the specified Element");
} else {
System.out.println("The specified Element is not in the List");
}
Object get(int index):
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
List list = new ArrayList();
list.add("Tom");
list.add("Smith");
list.add("Harley");
String output = list.get(2);
System.out.println("The Output: " + output);
The Output: Harley
Object set(int index, Object element):
Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).Object remove(int index):
Removes the element at the specified position in the list. It throws IndexOutOfBoundsException if the index out of range i.e index < 0 || index >= list.size().void ensureCapacity(int minCapacity):
Although the capacity of an ArrayList object increases automatically as objects are stored in it, you can increase the capacity of an ArrayList object manually by calling ensureCapacity( ). You might want to do this if you know in advance that you will be storing many more items in the collection that it can currently hold. By increasing its capacity once, at the start, you can prevent several reallocations later. Because reallocations are costly in terms of time, preventing unnecessary ones improves performance.void trimToSize():
Conversely, if you want to reduce the size of the array that underlies an ArrayList object so that it is precisely as large as the number of items that it is currently holding, call trimToSize().Object[] toArray():
When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. As explained earlier, you can do this by calling toArray( ). Several reasons exist why you might want to convert a collection into an array such as:- To obtain faster processing times for certain operations.
- To pass an array to a method that is not overloaded to accept a collection.
- To integrate your newer, collection-based code with legacy code that does not understand collections.
List list = new ArrayList();
list.add(1);
list.add(3);
list.add(5);
list.add(7);
Object[] intArray = list.toArray();
int sum = 0;
for (int i = 0; i < intArray.length; i++) {
sum += (Integer) intArray[i];
}
System.out.println("The Sum is:: " + sum);
The Sum is:: 16
public List subList(int fromIndex, int toIndex):
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
List alist = new ArrayList();
alist.add(10);
alist.add(20);
alist.add(30);
alist.add(40);
alist.add(50);
alist.add(60);
alist.add(70);
alist.add(80);
List sub = alist.subList(2, 4);
for (Integer i : sub)
System.out.println(i);
Leave a Comment