简体   繁体   English

带索引检索的排序数据结构

[英]Sorted Data Structure with index retrieval

Which Collection stores data in some specified order and can return or set elements according to index?哪个 Collection 以某种指定的顺序存储数据,并且可以根据索引返回或设置元素? I know that TreeSet implements SortedSet, hence stores data according to either natural ordering or some Comparator object provided by the programmer.我知道 TreeSet 实现了 SortedSet,因此根据自然顺序或程序员提供的一些 Comparator 对象存储数据。 But I don't know how to retrieve or set elements in a TreeSet using index.但我不知道如何使用索引检索或设置 TreeSet 中的元素。 On the other hand, ArrayList and some other structures can be used to retrieve or set their elements accoring to any index.另一方面,ArrayList 和其他一些结构可用于根据任何索引检索或设置其元素。 But they don't store elements in sorted order.但它们不按排序顺序存储元素。 Any way to have both features?有没有办法同时拥有这两个功能?

You can just use an ArrayList and sort it using Collections.sort .您可以只使用ArrayList并使用Collections.sort对其进行排序。 If you have to insert elements, you can find the insertion-point using Collections.binarySearch , giving you O(log n) complexity for insertions (as opposed to O(n log n) for resorting).如果您必须插入元素,您可以使用Collections.binarySearch找到插入点,为您提供 O(log n) 的插入复杂度(而不是 O(n log n) 的重新排序)。 ArrayList provides an overload of add that takes a position parameter . ArrayList提供了一个带位置参数的add重载

Take a look at indexed-tree-map https://github.com/geniot/indexed-tree-map I enhanced TreeMap to provide access and retrieval by index.看看 indexed-tree-map https://github.com/geniot/indexed-tree-map我增强了 TreeMap 以提供按索引的访问和检索。 To get the insertion index of a key which doesn't exist you can try to run the put-entryIndex-remove sequence.要获取不存在的键的插入索引,您可以尝试运行 put-entryIndex-remove 序列。 Although it may not be very efficient for your requirements.尽管对于您的要求可能不是很有效。 My entryIndex implementation is based on first finding the entry and then calculating its index.我的 entryIndex 实现基于首先找到条目然后计算其索引。 I will take a look if it can be improved for non-existing keys.我会看看它是否可以针对不存在的密钥进行改进。

You can't set elements by index in a sorted set without breaking accidentally the sorting order.您不能在不意外破坏排序顺序的情况下按排序集中的索引设置元素。 If you mean 'setting values of a map by key's index' then again you can use index-tree-map.如果您的意思是“通过键的索引设置地图的值”,那么您可以再次使用 index-tree-map。 Just find the key by index and use put to overwrite the value.只需通过索引找到键并使用 put 覆盖该值。

将元素填充到 ArrayList 中并通过调用 Collections.sort() 对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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