In: Computer Science
Java Problem:
Array lists and linked lists are both implementations of lists. Give an example of a situation where an array list would be the better choice and one where a linked list would. Explain the reasons in each case. Provide example.
Array List:
Array List is a resizable array that internally uses a dynamic array to store the elements. As we add elements to the array list, its size is increased dynamically. It is better for storing and accessing the data.
We can access the array list element directly by using the get() and set() method.
The syntax for the creation of the array list is given below:
ArrayList<Integer> al = new ArrayList<Integer>();
ArrayList is a better choice if your program is thread-safe.
If get()and set() operation are the major operations, then Array List would be the better choice because we can access the element directly.
Linked List:
A linked list is implemented by using the concept of the doubly-linked list. It can act as a list and queue both. It can be manipulated fast as compare to the Array List because no shifting is required.
It performs better when we add and remove element but it is very slow to get() and set() method.
The syntax for the creation of the linked list is given below:
LinkedList<String> ll=new LinkedList<String>();
Memory overhead is more in the Linked List implementation because we are storing pointer with data.
If insertion and deletion are the major operations then the Linked List would be the better choice because the time complexity is O(1).