简体   繁体   中英

Java random insert collection

I am considering using a Java collection that would work best with random insertions. I will be inserting a lot and only read the collection once at the end.

My desired functionality is adding an element at a specified index, anywhere between <0, current_length>. Which collection would be the most efficient to use?

Useful link for your reference: http://www.coderfriendly.com/wp-content/uploads/2009/05/java_collections_v2.pdf

Not entirely sure how you will be reading the information post input (and how important it is to you). Hashmap or ArrayList would make sense depending on what you are looking to do. Also not sure if you are looking for something thread safe or not. Hope it helps.

The inefficiency of using List is endemic to the problem. Every time you add something, every subsequent element will have to be re-indexed - as the javadoc states:

Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

From your question/comments, it would appear that you have a bunch of Object s, and you're sorting them as you go. I'd suggest a more efficient solution to this problem would be to write a Comparator (or make your object implement Comparable ), and then use Collections.sort(list, comparator) (or Collections.sort(list) ).

You might suggest that your Object s are being sorted on the basis of other variables. In which case, you could create an extension of the Object , with those other variables as fields and extending Comparable , and with a method like getOriginal() . You add these wrapped objects to your list, sort, and then iterate through the list, adding the original objects (from getOriginal() ) to a new list.

For info on the sorting algorithm of collections - see this SO question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM