Java Collections - ArrayList

Ashok Veer | April 25, 2020 | Be the first to comment!

Java Collections – ArrayList



ArrayList internally uses array data structure and ArrayList is resizable and growable array in nature which implements the List interface.

ArrayList increases its size internally when it reaches to its default capacity 10. In java project mostly java developer uses ArrayList because performance and other benefits.

public class ArrayList extends AbstractList
  implements List, RandomAccess, Cloneable, java.io.Serializable


Features of ArrayList class
  •   ArrayList class contains duplicate element.
  •  ArrayList class can follow the insertion order.
  •  Java ArrayList allows any number of null elements.
  •  ArrayList class also allows random access because in ArrayList internally arrays works on the index basic get(int index).
  •  ArrayList is not synchronized it means it is not thread safe,  If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
      List list = Collections.synchronizedList(new ArrayList(...));
  • In ArrayList primitive types are not allowed like int, float, char etc. We need to use wrapper classes such as Integer, Float.
  •    The Iterator return by the ArrayList iterator is fail-fast. If the ArrayList is structurally modified at any time after the iterator creation then  iterator will throw the runtime exception that is ConcurrentModificationException.

Performance of ArrayList / Complexity of java ArrayList

  •  Add(E e) – Adding an element in ArrayList gives the  O(1) performance
  •  get (int index) – In ArrayList getting an element is  gives O(1) performance, Because internally ArrayList uses array to store element so it is directly go for particular last  index to fetch element.
  • remove(int index) - In ArrayList getting an element is fast but removing an element is gives performance issue because of internal element shifting in the array so it gives O(1) for removing the first element and O(n) to last element.


 ArrayList example

package com.vr.techfloaters;

import java.util.ArrayList;

public class ArrayListExample {
    
           public static void main(String[] args) {
                ArrayList list = new ArrayList<>();
                list.add(50);
                list.add("veer");
                list.add(null);
                list.add("ashok");
                list.add(30);
                list.add(null);
               
                System.out.println(list);
           }
}

Output:

[50, veer, null, ashok, 30, null]


Click on below link for..
How ArrayList works internally  

0 comments:

Post a Comment

 
Copyright © 2019 techfloaters • All Rights Reserved.
Template Design by Ashok Veer ( veersoft solution)