ArrayLists: Dynamic Arrays in Java (Part 1)

Listen to this article

Before beginning this post, I would like to state that this post assumes some prior knowledge of Java (particularly arrays, classes and objects, and overriding)
The main limitation with arrays (groups of elements of the same datatype that are referenced by a common name) in Java is that they have a fixed size, and cannot shrink or grow in size. To overcome this, the ArrayList class can be used, which offers the functionality of a dynamic array. This class implements the List interface, which itself defines the methods used to manipulate ArrayLists. Both the class and the interface reside in the java.util package. This post deals with the functionality of various methods in the ArrayList class.
Adding elements to ArrayLists and Iterating through them:
The following example shows how to add elements to an ArrayList and iterate through them.
//Adding elements to an ArrayList and iterating through them
package codingexamples;
import java.util.*;
public class ArrayListExample1 {
    public static void main(String[] args){
        List<String> list = new ArrayList<>();    //works in Java 7 and above
        list.add(“Apple”);
        list.add(“Banana”);
        list.add(“Grapes”);
        list.add(1, “Watermelon”);              //insert “Watermelon” at position 1       
        System.out.println(list);               //prints out names of elements
        System.out.println();
               //iterate through elements using enhanced for loop
        for(String s : list)
            System.out.println(s);
            System.out.println();
            //iterate through elements using ListIterator
        ListIterator<String> itr = list.listIterator();
        while(itr.hasNext())
            System.out.println(itr.next());
        }   
}
The output of the code is:
[Apple, Watermelon, Banana, Grapes]
Apple
Watermelon
Banana
Grapes
Apple
Watermelon
Banana
Grapes
The first line marked in bold shows how to create an ArrayList. Note the use of angle brackets in this line. ArrayList can work with multiple object types (it is a generic collection), and the type to be stored (in this case String) must be specified in the angle brackets, making ArrayLists type safe. Also, as mentioned earlier, ArrayList implements the List interface, and all the methods commonly used with ArrayLists are defined in this interface itself. So, a List reference may be used to store an ArrayList object, as shown in this line. As of Java 7, the angle brackets on the right side of the ‘=’ sign can be left empty. So prior to Java 7, you would have had to write,
List<String> list = new ArrayList<String>();
The next few lines add elements to the ArrayList. While the elements “Apple”, “Banana” and “Grapes” are added to the end of the list each time (using the single argument add() method), the element “Watermelon” is inserted at position 1 (so that it is the second element, as the numbering starts from 0), using the two-argument add() method. The remaining elements are shifted ahead by one position when this happens.
In the next line, the list is passed to the println() method, which shows the elements of the ArrayList in order, in agreement with the add() method calls. And finally, the elements of the ArrayList are iterated through, using an enhanced ‘for’ loop and a ListIterator (observe the syntax when using ListIterator).

Modifying and Deleting Elements:
The following example shows how to modify and delete elements from an ArrayList:
//Modifying and deleting elements of an ArrayList
package codingexamples;
import java.util.*;
public class ArrayListExample2 {
    public static void main(String[] args){
        ArrayList<String> list = new ArrayList<>();
        list.add(“Apple”);
        list.add(“Banana”);
        list.add(“Grapes”);
        list.add(1, “Watermelon”);
        list.add(“Apple”);
       System.out.println(list);
     
        list.set(2, “Pomegranate”);      //modify element at index 2
       
        System.out.println(list);
       
        list.remove(2);                 //remove element at index 2
        list.remove(“Apple”);           //remove first occurrence of “Apple”
       
        System.out.println(list);
       
        list.clear();                   //clear the ArrayList
       
        System.out.println(list);
    }
}
The above code outputs:
[Apple, Watermelon, Banana, Grapes, Apple]
[Apple, Watermelon, Pomegranate, Grapes, Apple]
[Watermelon, Grapes, Apple]
[]
The first line of output shows the initial contents of the ArrayList. Then the set() method is used to modify the element at index 2 (that is the third element), which is reflected in the second line of output. After this, the element at index 2 and the element “Apple” are removed using the remove() method. But since the element “Apple” occurs twice in the ArrayList, only the first occurrence of the element is removed. The effect of this is shown in the third line of output. Finally the clear() method is used to clear the ArrayList, which is shown in the fourth line of output.
With this we come to the end of Part 1 of this post. For more information on ArrayLists, please do read Part 2 of this post which will be published on Friday, July 5th, 2019…

(Visited 225 times, 1 visits today)

Related Posts

Leave a Reply