8 Must Know ArrayList Read Operations for Java Developers

Hello Friends,

In this article,we will see all the read operations which can be performed on one of the very commonly used collection i.e. ArrayList.If you want to see all the write operations which can be performed on an ArrayList,you can go through my previous article ArrayList Write operations explored.



Lets discuss read operations on ArrayList one by one.

1) How to read/get elements of an ArrayList

In the last article we saw that how we can add elements in an arrayList. Now let us see how we can read or get element added in the arrayList.

Getting elements from arrayList one at a time using get(index) method

List list<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
Now say we want to get element at position 1 in the list.We can do something like below 
list.get(1);
Output :
b

What if we want all the elements of list ?

Looping through all elements with for loop

Very simple. loop through elements of list. Here size() method gives the size of an arrayList , i.e. actual number of elements contained within arrayList.So in our case size() method will return 3.If you want to know the difference between size and capacity of an arrayList,you can go through my previous article  ArrayList features every Java developer must know.
for(int i=0;i<list.size();i++){
  System.out.println(list.get(i));
}
Output :
a
b
c
Looping through all elements with iterator
List list<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
Iterator<String> itrList = list.iterator();
while(itrList.hasNext()){
 String ele = (String)itrList.next();
 System.out.println(ele);
}
Output
a
b
c
Did you wonder  on following line in above program
Iterator<String> itrList = list.iterator();
basically what this line is doing...it is calling iterator() method on list which is returning an instance of type Iterator, but we know that Iterator is an interface and we also know very well that interfaces could not be instantiated, then how come iterator() method is returning instance of type Iterator.

Lets check source code of iterator method in java.util.ArrayList class
public Iterator<E> iterator() {
        return new Itr();

}
So what it is doing is....it is returning an instance of Itr class..but what is this Itr class.Lets check that...
private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
So from above code, we can see that when we call iterator() method on list, it will return instance of a class(Itr) which is a inner class within java.util.ArrayList class and implements Iterator interface.

Along with above two methods,there are various other ways we can get/iterate over elements of an arrayList.To know all the methods of iterating over arrayList,please go through my earlier article Various ways to iterate over commonly used collections.

Getting all the elements of an arrayList in one go in an Array using toArray() method
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
  
Object[] arList = list.toArray();
for(int i=0;i<arList.length;i++){
 System.out.println(arList[i]);
}

toArray() method returns an array containing all of the elements in this list from first to last .The returned array will be "safe" in that no references to it are maintained by this list. In other words, this method must allocate a new array to store the elements of list. The caller is thus free to modify the returned array.

Getting all the elements of an arrayList in one go in an Array using toArray(T[] a) method

Example 1 

Size of the array passed to toArray is equal to the size of the arrayList
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
 
String ab[] = new String[3];
 
ab = list.toArray(ab);
for(int i=0;i<arList.length;i++){
 System.out.println(arList[i]);
}
Output 
a
b
c
In this case elements of an arrayList are stored in the array passed to the toArray method.As size of array is equal to the number of elements of list,toArray method uses this array to store elements on the arrayList.

Example 2 

Size of the array passed to toArray is less than the size of the arrayList 
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
  
String ab[] = new String[0];
  
String[] arList = list.toArray(ab);
for(int i=0;i<arList.length;i++){
 System.out.println(arList[i]);
}
Output 
a
b
c

As in this case size of array passed to to toArray method is less than the size of arrayList, toArray method will
not be able to store elements of arrayList in this array, so it will check runtime type of array passed and will
create a new array with length equal to the size of the arrayList and store elements in it. As in this case
toArray method has to do some extra work of checking runtime type of array and then creating a new array,
this method is less efficient than example 1.

Example 3

Size of the array passed to toArray is more than the size of the arrayList 

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
    
String ar[] = new String[5];
    
ar = list.toArray(ar);
for(int i=0;i<ar.length;i++){
  System.out.println(ar[i]);
}

Output 
a
b
c
null
null
As in this case size of the array passed to the toArray method is more than size of the the arrayList, toArray
method will populate the remaining positions of the array with null.

Additional Info : This method will throw ArrayStoreException if the runTime type of the array is not
superType of runtime type of the each of element of an ArrayList.

Example
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
    
Integer ar[] = new Integer[3];
    
ar = list.toArray(ar);
for(int i=0;i<ar.length;i++){
  System.out.println(ar[i]);
}
Output 
Exception in thread "main" java.lang.ArrayStoreException
 at java.lang.System.arraycopy(Native Method)
 at java.util.ArrayList.toArray(ArrayList.java:306)
 at com.gb.exceptionHandling.Customer.main(Customer.java:31)

2) How to get sublist from a list using subList method

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");

System.out.println("complete list before calling subList");
for(String str : list){
  System.out.println(str);
}
  
List<String> sublist = list.subList(1, 3);
System.out.println("Sublist after calling subList method");

for(String str : sublist){
  System.out.println(str);
}
Output :
complete list before calling subList
a
b
c
Sublist after calling subList method
b
c
subList method extracts elements from fromIndex (1) to toIndex(3).fromIndex is inclusive which means element at postion of fromIndex will be extracted,but toIndex is exclusive which means element at position of toIndex is not extracted,but toIndex-1 is extracted.

In our case element at position of fromIndex(1) was "b" and element at position of toIndex-1(2) was c,so sublist will contain b and c.

toIndex can be maximum upto size of the list.If it is greater than that ,you will get indexOutOfBoundException.

fromindex should not be less than zero.if it is less than zero,then also you will indexOutOfBoundException.

What if you give fromIndex and toIndex as same

Lets check by executing a small program
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");

System.out.println("complete list before calling subList");
for(String str : list){
  System.out.println(str);
}
  
List<String> sublist = list.subList(1, 1);
System.out.println("Sublist after calling subList method");

for(String str : sublist){
  System.out.println(str);
}

System.out.println("After printing sublist");
Output:
complete list before calling subList
a
b
c
d
Sublist after calling subList method
After printing sublist
So from above output,we can see that nothing is returned when fromIndex and toIndex are same.

3) How to check if an element exists in the ArrayList

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");

if(list.contains("a")){
 System.out.println("List Contains element a");
}

if(list.contains("d")){
   System.out.println("List Contains element d");
}else{
  System.out.println("List does not contain element d");
}
Output :
List Contains element a
List does not contain element d
contains method returns true if an element passed to it exists in the list, else it will return false.

4) How to check if all of the elements  of a collection exist in the list

Checking whether a list exist within another list

Example 1


All elements of anotherList are present in the original list

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");

List<String> anotherList = new ArrayList<String>();
anotherList.add("c");
anotherList.add("d");

if(list.containsAll(anotherList)){
 System.out.println("list contains anotherList");
}else{
 System.out.println("list does not contain anotherList");
}
Output :
list contains anotherList

Example 2

Not all the elements of anotherList are present in the original List

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
  
List<String> anotherList = new ArrayList<String>();
anotherList.add("c");
anotherList.add("d");

if(list.containsAll(anotherList)){
 System.out.println("list contains anotherList");
}else{
 System.out.println("list does not contain anotherList");
}
Output:
list does not contain anotherList
As both the elements of anotherList are not present in the original list,containsAll returned false.

5) How to find index of an element of an ArrayList
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");

int index = list.indexOf("c");
System.out.println("Index of element c in the list:"+index);
Output : 
Index of element c in the list:2

6) How to check if a list is empty 

Example 1 :

List with three elements
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
if(list.isEmpty()){
 System.out.println("List is empty");
}else{
 System.out.println("List is not empty");
}
Output :
List is not empty

Example 2 :

List with  nothing added to it

List <String> list = new ArrayList<String>();
if(list.isEmpty()){
 System.out.println("List is empty");
}else{
 System.out.println("List is not empty");
}
Output :
List is empty

Example 3:

List with null value

List <String> list = new ArrayList<String>();
list.add(null);
System.out.println("List Size:"+list.size());
if(list.isEmpty()){
 System.out.println("List is empty");
}else{
 System.out.println("List is not empty");
}
Output :
List Size:1
List is not empty

7) How to find index of the last occurrence of element in the list

Example 1 :

When element is present in the list

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("a");
int index = list.lastIndexOf("a")
System.out.println("Last index of a is :"+index);
Output :
Last index of a is :3

Example 2 :

When element does not exist in the list

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("a");
int index = list.lastIndexOf("d")
System.out.println("Last index of d is :"+index);
Output :
Last index of a is :-1

8) How to check if two lists are equal

Two lists will be considered as equal only and only if both the lists have same size and both lists have equal elements at corrresponding positions in both the list.

Example 1 :

When both the lists have same size and both have elements in the same order
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
  
List<String> anotherList = new ArrayList<String>();
anotherList.add("a");
anotherList.add("b");
anotherList.add("c");
boolean flag = list.equals(anotherList);
if(flag){
 System.out.println("Equal");
}else{
 System.out.println("Not Equal");
}
Output :
Equal

Example 2 :

When both the lists have same size but order of elements in both the lists are not same

List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
  
List<String> anotherList = new ArrayList<String>();
anotherList.add("a");
anotherList.add("c");
anotherList.add("b");
boolean flag = list.equals(anotherList);
if(flag)
 System.out.println("Equal");
}else{
 System.out.println("Not Equal");
}
Output :
Not Equal


Example 3 :

How to overcome the problem in example 2


Sort the elements of both the list,which will make sure that elements in both the lists are in same order and then you can check for equality.
List <String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");

//Sort the elements of list  using static method sort of Collections class 
Collections.sort(list);
  
List<String> anotherList = new ArrayList<String>();
anotherList.add("a");
anotherList.add("c");
anotherList.add("b");
 
//Sort the elements of list  using static method sort of Collections class
Collections.sort(anotherList);
  
boolean flag = list.equals(anotherList);
if(flag){
 System.out.println("Equal");
}else{
 System.out.println("Not Equal");
}

Output
Equal
That's all on read operations on ArrayList. Hope this was helpful. Any feedback, comments, suggestions, queries are most welcome.