Java Collection framework provides an ArrayList class in package java.util which is used to hold a collection of objects. It implements the List interface(List extends Collection interface).The benefit of using ArrayList over Array is that you do not need to know the size of ArrayList<E> while creating it. It could be thought of as a dynamic array. Rather, its internal implementation makes use of an array to hold its elements.
ArrayList support generics to help you with type-safety. It maintains the insertion order of its elements.
An ArrayList can be created using any of the following constructors :
ArrayList() // initialCapacity is 10 ArrayList(int initialCapacity) ArrayList(Collection<? extends E> c)
For the OCA Java Exam you are expected to identify valid ways of ArrayList creation.
I. ArrayList<String> arrList = new ArrayList<String>(); //use of diamond operator II. ArrayList<String> arrList = new ArrayList<>(); III. List<String> arrList = new ArrayList<>(); IV. List<String> arrList2 = new ArrayList<>(arrList); V. List<String> arrList = new ArrayList<>(20); VI. List<String> arrList = new ArrayList();
For point (VI.) , the compiler will throw an unchecked warning but the compilation still works fine.
List<Integer> listInt = new ArrayList<>(); listInt.add(1); listInt.add(2); List<String> listStr = new ArrayList(listInt); //works fine System.out.println(listStr.get(0)); // throws ClassCastException
Adding Elements : Below are some available methods that can help you add items to an ArrayList.
boolean add(E element) void add(int index, E element) boolean addAll(Collection<? extemds E> c) boolean addAll(int index, Collection<? extends E> c)
add(E element) or addAll(Collection c) methods add the elements to the end of the list.
add(int index, E element) & addAll(int index, Collection c) methods add the given value to the specified index by shifting elements starting from that index towards the end of the list , in order to make sufficient room. If the index is invalid(index < 0 || index >= size()), this method throws IndexOutOfBoundException.
The boolean return type specifies that the method returns true if the insertion succeeds.
Example Usage :
List<String> list = new ArrayList<>(); list.add("Harry"); list.add("Jack"); list.add("James"); list.add(1,"Vit"); //prints [Harry, Vit, Jack, James] System.out.println(list);
Removing Elements : Below set of methods can help us when trying to remove an element from ArrayList.
E remove(int index) boolean remove(Object element) boolean removeAll(Collection<?> c) boolean removeIf(Predicate<? super E> filter)
remove(int index) method removes and returns the element at that index. If index is out of range, it throws IndexOutOfBoundException.
remove(Object obj) methods removes the first matching occurrence of object element in the ArrayList. It returns true if the call was successful.
removeAll() methods removes from an ArrayList – all the elements which matches elements in given collection.
removeIf() method removes from an ArrayList all the elements that satisfy the filtering criteria defined by a lambda expression of type Predicate.We’ll cover about it in detail in an upcoming post.
Both removeAll() & removeIf() returns true if the call was successful.
We have already covered StringBuilder & String in our previous posts . If you have gone through it well, hopefully you’ll be in a position to answer the below question :
import java.util.*; public class Test{ public static void main(String []args){ List<String> list1 = new ArrayList<>(); list1.add(new String("Harry")); list1.add(new String("Jack")); list1.remove(new String("Jack")); System.out.println(list1); //prints [Harry] List<StringBuilder> list2 = new ArrayList<>(); // StringBuilder jack = new StringBuilder("Jack"); list2.add(new StringBuilder("Harry")); list2.add(new StringBuilder("Jack")); StringBuilder jack2 = new StringBuilder("Jack"); System.out.println(list2.contains(jack2));//false System.out.println(list2.indexOf(jack2));//-1 list2.remove(new StringBuilder("Jack")); System.out.println(list2); //prints [Harry, Jack] List<StringBuilder> list3 = new ArrayList<>(); StringBuilder jack = new StringBuilder("Jack"); list3.add(new StringBuilder("Harry")); list3.add(jack); list3.remove(jack); System.out.println(list3); //prints [Harry] } }
Unlike String, the StringBuilder class doesn’t overrides equals() method.So, when you call remove() on list2 , default equals() method from the Object class is executed which only makes a reference comparison so the match fails. In case of list3 we are providing the same reference so the element match succeeds and it gets removed the list.
I know this was real brainstorming session. So, let’s keep it a little lighter moving forward, at least for some time from now. So let’s cover some other methods in ArrayList class.
void trimToSize()
void clear()
int size()
boolean isEmpty()
E get(int index)
E set(int index, E element)
boolean equals(Object obj)
boolean contains(Object element)
int indexOf(Object element) int lastIndexOf(Object element)
List<Integer> arrList = new ArrayList<>(); arrList.add(1); arrList.add(2); arrList.add(3); arrList.add(4); //using for loop for(int i=0; i< arrList.size(); i++){ System.out.println(arrList.get(i)); arrList.remove(i); //throws ConcurrentModificationException } //using forEach loop for(int element : arrList){ System.out.println(element); }
ListIterator itr = arrayList.listIterator(); while(itr.hasNext()){ System.out.println(itr.next()); }
Let’s look at some differences between Iterator and a ListIterator.
Iterator | ListIterator |
---|---|
Methods : hasNext() next() remove() | Methods : add(E e) hasNext() hasPrevious() next() nextIndex() previous() previousIndex() remove() set(E e) |
Cannot replace the existing element | Can replace the existing element |
Cannot add element to collection while traversing it | Can add element to collection while traversing it |
Can traverse in only forward direction | Can traverse in both directions |
It can be achieved using the toArray() method. Note that if you modify the output array say by swapping its elements or so it will not impact the ArrayList. However, if you modify the state of elements of the returned array then the modified state of elements will be reflected in the ArrayList.
Object[] toArray();
Sorting an ArrayList can be achieved using a sort() method available in java.util.Collections class.
Collections.sort(List<E> list)
This was an eye opener and I have learnt alot from this tutorial. Please keep them coming.
Thanks..Appreciate your positive feedback!