The java.util.LinkedList does not allow you to quickly remove a given object in the list. The remove(object) method performs a linear search to find the object in the list so it can remove it. Since this is a double linked-list, it would be nice to remove by just updating the pointers (node.prev and node.next).
What is the Java standard solution for this problem?
NOTE1: I don't want to remove while iterating. I know that is fast, but I am not iterating through my elements in the first place.
NOTE2: To make it simple: Given an object O that I know it is in a double linked-list, I want to quickly remove O from that list (by updating the pointers) without having to linear search for it in the list, as java.util.LinkedList does.
ArrayList is slow as array manipulation is slower. LinkedList is faster being node based as not much bit shifting required. ArrayList implements only List. LinkedList implements List as well as Queue.
To delete a node from the linked list, we need to do the following steps: Find the previous node of the node to be deleted. Change the next of the previous node. Free memory for the node to be deleted.
To delete a node from the linked list, we need to do the following steps. 1) Find the previous node of the node to be deleted. 2) Change the next of the previous node. 3) Free memory for the node to be deleted.
The insertion and deletion in a singly-linked list are less complex than a doubly linked list. If we insert an element in a singly linked list then we need to update the address of only next node.
You should take a look at the LinkedHashSet class. Basically it's a HashSet that maintains a doubly-linked list among its entries. It supports retrieval (and thus also deletion) of an element in O(1) (hopefully). Check the link for the specification on the how it handles the elements order in case of reinserting an entry and other details.
EDIT:
If you need to store duplicates you can take a look at the Guava LinkedHashMultiset (never used so far). The Guava user guide on Multiset is here.
I bet you that the implementation of LinkedList#remove()
does remove it by updating the pointers to the previous and next items - the problem is, it has to loop over all objects until it finds the proper one to remove.
If you want a collection that removes faster, without iterating over all the objects, use a Set
or a Map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With