How do I efficiently remove a node from java's LinkedList by reference to an object, or to a specific node? using remove(object) uses a traversal over the whole list, as evidenced by the documentation: "removes the first element e such that (o==null ? e==null : o.equals(e))". Can I remove by specific reference to a node? I don't mind storing the reference to the node in the object itself. I can't use the index of the list, as it may change. If not, is there another data structure which would allow me to do this?
2 Answers
Try using a LinkedHashSet. It's basically a HashSet with a deterministic ordering to its elements. Or alternatively, you can view it as a LinkedList backed with by an element look-up table.
I believe the remove(Object) operation will be constant-time.
2 Comments
You may want to use a HashSet
Deletion, insertion are in general in constant time, as stated by the official API :
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets
If you decide to use a HashSet, don't forget to override both equals AND hashcode methods in your object.
2 Comments
LinkedHashSet. But hashing is not "a workaround"
LinkedList? If your own it depends on how you implemented it. What have you tried? Can you post relevant code, and describe the issue you are having? As for other data structures, it depends on your requirements. You have to be more specific.