Difference between ArrayList and LinkedList in Java
ArrayList
and LinkedList
are the two general-purpose List
implementations.
Even though ArrayList
is the favorite of java developers, a smart choice between these two classes will definitely improve the performance of your application.
- ArrayList is most suitable when your list is having a fixed number of objects and you are using this list only for retrieving the objects.
- The time required to access any object from an ArrayList is the same. ArrayList is just plain fast.
- Addition and removal of objects from an ArrayList take more time when compared to a LinkedList since these operations are linear in ArrayList.
- ArrayList is maintaining a tuning parameter called
initial capacity
which refers to the number of objects it can hold before we can start adding objects into it. - ArrayList implements the
List
interface.
- LinkedList is more suitable when you frequently add objects to the list and delete from the list.
- Positional access of objects from a LinkedList requires linear-time. Means more time when compared with an ArrayList.
- Addition and removal of objects from a LinkedList is faster when compared to an ArrayList since these operations require constant time for all the objects.
- LinkedList doesn't maintain any tuning parameter like ArrayList, but it offers seven optional operations.
clone
: Returns a shallow copy of the original list. Only the list object will be cloned, not it's elementsaddFirst
: Inserts the given object at the beginning of the list.addLast
: Inserts the given object at the end of the list.getFirst
: Returns the first object in the list.getLast
: Returns the last object in the list.removeFirst
: Removes and returns the first object from the list.removeLast
: Removes and returns the last object from the list.
- LinkedList implements
List
andQueue
interfaces.
How to avoid NullPointerException in Java
NullPointerException will be thrown when an application attempts to use null in a case where an object is required. Read More
Difference between replace() and replaceAll() in Java
replace() will replaces all occurrences of oldChar in the string that invokes the method with newChar. Then why we need replaceAll()? Read More
How to compare strings in java
Strings in java can be compared either by using the operator == or by using the method equals(). intern() can generate a canonical representation of the string object. Read More