Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java linked list that supports fast removal of any nodes?

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.

like image 267
chrisapotek Avatar asked Feb 07 '12 15:02

chrisapotek


People also ask

Why ArrayList is faster than LinkedList?

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.

How do you delete multiple nodes in a linked list?

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.

How do you remove a node from a linked list in Java?

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.

In which linked list the deletion operation is less costly?

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.


2 Answers

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.

like image 165
Marsellus Wallace Avatar answered Sep 27 '22 22:09

Marsellus Wallace


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.

like image 33
Marcelo Avatar answered Sep 27 '22 22:09

Marcelo