8

I need an ordered data structure with O(1) indexOf operation. I store object pointers in the data structure. Any ideas? Some sort of LinkedHashMap?

See what "indexOf" means: List.indexOf(Object)

5 Answers 5

7

This question is ambiguous to begin with.

  1. It would be nice if you could qualify what you mean by fast indexOf(..) operation.
  2. What kind of objects are you going to store in the collection?
  3. Is finding the indexOf(..) the only responsibility of the collection.

Simply put, one way to do this would be to maintain a that would index each Object or keys with the list of indices.

HashMap<Object, List<Integer>>

Again, this is vague, probably would help if you specify the exact nature of problem you're trying to solve.

Sign up to request clarification or add additional context in comments.

3 Comments

Then why not have another data structure that stores references to each object in the original list?
I have to maintain HashMap<Object, List<Integer>> each time I insert or remove objects from the main data structure? Isnt there such one data structure to do this.
By a datastructure you mean in Java collections - then No. If you mean if there is a User-Defined data structure or means to do it then of course.
2

Sounds like you want a SortedMap, TreeMap being the reference implementation. The performance is log(n), and that's probably the best you are going to get using lookup in an ordered structure (at least in standard libraries).

Comments

1

If you use a skip list or a balanced tree, you can get O(log n) for insert and indexOf.

If you maintain a sorted List<Object> to store the items you want to track, along with a HashMap<Object, Integer> to store the starting position of each item, you can get O(1) indexOf in exchange for O(n) insert.

I haven't thought about it deeply, but I don't think it's possible to get O(1) insert and O(log n) indexOf.

Comments

0

try using PriorityQueue instead to make it oredered...

1 Comment

? HashMaps arent even ordered.
0

Store the Object as both key and value in HashMap. I am assuming that you are looking to retrieve object eventually.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.