Thursday, January 17, 2013

java.util.Arrays.ArrayList

We are not discussing about the ArrayList class which is there in java.util package.

The ArrayList class that comes under java.util.Arrays is a private static nested class inside Arrays class.
This class implements List interface and extends AbstractList class.

It doesnot provide implementation for all the methods of List Interface. Infact it provides implementation to very few methods.

Methods in Arrays$ArrayList:-

public boolean contains(Object object)
public E get(int location)
public int indexOf(Object object)
public int lastIndexOf(Object object)
public E set(int location, E object)
public int size()
public Object[] toArray()

So if we will try access any other methods of List using runtime polymorphism it will access the method in AbstractList class. Hence throw an Exception if it is thrown in the AbstractList class.

Ex:- If we try to access add(Object obj) or remove(int location) it will throw UnsupportedOperationException.

Lets consider below scenario

List<String> list = Arrays.asList("tom","pom","kom","bom");
Iterator<String> i = list.iterator();
while(i.hasNext())
{
if(i.next().equals("pom"));
i.remove();//Exception thrown at this line
}


The above code will compile successfully but exception will be thrown at runtime when we will try to invoke remove();

Reason:- When we invoke remove() Iterator tries to invoke the remove(int location) of ArrayList class which is there in Arrays class. Since ArrayList class of Arrays class does not provide implementation for remove(int location) method it invokes remove(int location) of AbstractList class. Hence throws an UnsupportedOperationException.






No comments:

Post a Comment