Which Collection stores data in some specified order and can return or set elements according to index? I know that TreeSet implements SortedSet, hence stores data according to either natural ordering or some Comparator object provided by the programmer. But I don’t know how to retrieve or set elements in a TreeSet using index. On the other hand, ArrayList and some other structures can be used to retrieve or set their elements accoring to any index. But they don’t store elements in sorted order. Any way to have both features?
Which Collection stores data in some specified order and can return or set elements
Share
You can just use an
ArrayListand sort it usingCollections.sort. If you have to insert elements, you can find the insertion-point usingCollections.binarySearch, giving you O(log n) complexity for insertions (as opposed to O(n log n) for resorting).ArrayListprovides an overload ofaddthat takes a position parameter.