Saturday, July 25, 2020

ArrayList


public class ArrayList
 extends AbstractList
  implements List, RandomAccess, Cloneable, Serializable
All Implemented Interfaces:
Serializable, Cloneable, Iterable, Collection, List, RandomAccess

Direct Known Subclasses:
AttributeList, RoleList, RoleUnresolvedList

ArrayList class is resizable-array (dynamic array) implementation of the List interface.It is a part of collection framework and is present in java.util package. it is based on an Array data structure. Internally its use Object[].
Default capacity or size of ArrayList is 10.


Data Growth Of ArrayList:-
ArrayList grows (increments) 50% of the current array size automatically if the number of elements exceeds its capacity.


Load Factor Of ArrayList is 1.
The load factor is a measure of how full the array list is allowed to get before its capacity is automatically increased.


Note:- ArrayList() is slow as compared to array().

ArrayList can store only objects, not primitives that means if we store primitive types like int, char etc. it we be autoboxed to wrapper classes of same types like Integer, Character, Boolean etc.

If we try to create ArrayList with primitive types it will show as below "Syntax error"

ArrayList<int> listInt = new ArrayList<int>();
Syntax error, insert "Dimensions" to complete ReferenceType


Right way to use primitive type.

package com.shubh.example;
import java.util.ArrayList;

public class ArrayListExample {
 public static void main(String[] args) {
  ArrayList listInt = new ArrayList();
  listInt.add(10); // It will autoboxing to Integer wrapper class.
  System.out.println(listInt);
 }
}

Q- Is arraylist is thread safe?
Answer:- No.

Q- Is ArrayList synchronized?
Answer:- No.

Q- How to make arraylist synchronized or thread safe? Or How to synchronize ArrayList?
We can use Collections.synchronizedList() to synchronize ArrayList.
Collections.synchronizedList() method – It returns synchronized list backed by the specified list.
CopyOnWriteArrayList class – It is a thread-safe variant of ArrayList.


package com.shubh.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListExample {
 public static void main(String[] args) {
  ArrayList<Integer> listInt = new ArrayList<Integer>();
  listInt.add(10); // It will autoboxing to Integer wrapper class.

  List<Integer> listIntSyn = Collections.synchronizedList(listInt);
  System.out.println(listIntSyn);
  // OR
  ArrayList<Integer> listIntSyn2 = (ArrayList<Integer>) Collections.synchronizedList(listInt);
  System.out.println(listIntSyn2);
 }
}

Constructors of Java ArrayList:
  • ArrayList(): It is used to create an empty arraylist that means default size is 10.
  • ArrayList(Collection<? extends E> c): It is used to create an arraylist that is initialized with the specified collection c.
  • ArrayList(int capacity): It is used to create an arraylist with specified initial capacity.

Methods of Java ArrayList
  • boolean add(E e): To add an element at the end of a list.
  • void add(int index, E element): To add an element at the specified position in a list.
  • boolean addAll(Collection<? extends E> c)
  • boolean addAll(int index, Collection<? extends E> c)
  • void clear()
  • void ensureCapacity(int requiredCapacity)
  • E get(int index)
  • boolean isEmpty()
  • int lastIndexOf(Object o)
  • Object[] toArray()
  • <T> T[] toArray(T[] a)
  • Object clone()
  • boolean contains(Object o)
  • int indexOf(Object o)
  • E remove(int index)
  • boolean remove(Object o)
  • boolean removeAll(Collection<?> c)
  • boolean removeIf(Predicate<? super E> filter)
  • protected void removeRange(int fromIndex, int toIndex)
  • void replaceAll(UnaryOperator<E> operator)
  • void retainAll(Collection<?> c)
  • E set(int index, E element)
  • void sort(Comparator<? super E> c)
  • Spliterator<E> spliterator()
  • List<E> subList(int fromIndex, int toIndex): It the list  of elements lies within the given range.
  • int size() : It return the number of elements available in the list.
  • void trimToSize()
Q- Is Arraylist fail fast or fail safe?
ArrayLists are fail-fast.

Q- Dynamic array in java without arraylist?
Custom Own ArrayList Implementation

Summary of ArrayList:-
  • ArrayList class can contain duplicate elements and null values.
  • ArrayList  maintains the insertion order i.e it is an ordered collection.
  • ArrayList can store only objects, not primitives  that means if we store primitive types like int, char etc. it we be autoboxed to wrapper classes of same types like Integer, Character, Boolean etc.
  • ArrayList is non-synchronized.
  • ArrayList allows ramdom access because array work on index basis.
  • Default Capacity is 10
  • Load Factor is 1
  • Threshold value = Initial_Size * Load_Factor i.e 10*1 = 10
  • Growth Rate is 50% i.e Cutrrent_Size + Current_Size/2 
  • ArrayList() is slow as compared to array().
Time complexity
  • add() – O(1) time when add new element in ArrayList; however, worst-case, when increase size internaly and a new array has to be created and all the elements copied to it, it's O(n)
  • add(index, element) –  O(n) time, on average runs, while add element at given index
  • get() – It is always a constant time O(1) operation
  • remove() – runs in linear O(n) time. We have to iterate the entire array to find the element qualifying for removal.
  • indexOf() – its checks each element one by one, So runs in linear time. It iterates through the internal array and  so the time complexity for this operation always requires O(n) time.
  • contains() – implementation is based on indexOf(), so it'll also run in O(n) time.



No comments:

Post a Comment