80 likes | 170 Views
Comparison of ArrayList Efficiency to LinkedList. Computer Science 4 Mr. Gerb. Reference: Objective: Understand the differences between the efficiencies of LinkedLists and ArrayLists. Add, Size, Clear. Add Adds to end of list In ArrayList might need to resize list
E N D
Comparison of ArrayList Efficiency to LinkedList Computer Science 4 Mr. Gerb Reference: Objective: Understand the differences between the efficiencies of LinkedLists and ArrayLists.
Add, Size, Clear • Add • Adds to end of list • In ArrayList might need to resize list • In LinkedList, simply add to the back of the list (LinkedList keeps a reference to the last node) • Size: Same for ArrayLists as LinkedLists. Both keep track of the size of the list • Clear • ArrayList sets the size to 0 • LinkedList sets the front and back pointers to null. Nodes in the list are garbage-collected • Both O(1)
Get and Set • Get(int n) - Get the nth item in the list • O(1) in ArrayList. Simply retrieve desired Object • Much slower in LinkedList (O(N)) • Pointers are not kept to each element in the list • Method must “count” nodes to the Nth • Set(int n, Object ob) - Set the nth item in the list • Also O(1) in ArrayList. Simply set the desired element. • Also much slower in LikedList (O(N)). Must count nodes.
Remove Remove(int n) - Remove and return nth element: • O(N) in ArrayList. Must move all subsequent elements down one position. Takes an average of N/2 moves. • O(N) in Linked list: • The removal is easy (O(1), need only to change the pointers on the next and previous nodes. • But must count nodes to reach the node to be removed. • Thus remove is O(N) for both ArrayLists and LinkedLists.
Additional operations provided by LinkedList • getFirst – O(1) in both ArrayList (as get(1)) and LinkedList • getLast – O(1) in both ArrayList (as get(list.size())) and LinkedList • removeFirst – O(N) in ArrayList (as remove(1)) but O(1) in LinkedList. • removeLast – O(1) in both ArrayList (as remove(list.size())) and LinkedList • addFirst - O(1) in Linked List. Unavailable in ArrayList.
Summary • Compared to ArrayLists: • LinkedList is more efficient for adding (no resizing) • LinkedList is less efficient for getting and setting a specified element. (LinkedList must count nodes). • LinkedList’s additional capabilities • All O(1) • removeFirst is more efficient than O(N) ArrayList • addFirst is unavailable in ArrayList