Why is there only a SortedList<TKey, TValue>
which looks more like a dictionary, but no SortedList<T>
that is actually just a list that is always sorted?
According to the MSDN documentation on SortedList, it is actually internally implemented as a dynamically-sized array of KeyValuePair<TKey, TValue>
that is always sorted by the key. Wouldn’t the same class be more useful as a list of any type T
? Wouldn’t that fit the name better, too?
Tree by definition cannot contain duplicates. In List we can have duplicates, so there is no TreeList (i.e. no SortedList ). List maintains elements in insertion order. So if we want to sort the list we have to use java.
SortedDictionary is implemented with Binary Search Tree, while SortedList is implemented with two internal arrays for keys and values, respectively. SortedList is more memory-efficient than SortedDictionary, and SortedList is faster than SortedDictionary when it needs to go through all items at once.
A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.
A SortedList does not allow duplicate keys. Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. Elements in this collection can be accessed using an integer index.
Although nobody can really tell you why there is no SortedList<T>
, it is possible to discuss why SortedList
takes a key and a value. A dictionary maps keys to values. The typical ways to do this are with a binary tree, a hash table, and a list (array), though hash tables are most common because they are O(1) for most operations.
The primary operation that it doesn't support in O(1) is getting the next key in order. If you want to be able to do that, you typically use a binary tree, giving you a sorted dictionary.
If you decide to implement the map as a list, you would keep the elements sorted by key so that lookup is O(lg n), giving you another sorted dictionary -- in the form of a sorted list. Of course the name SortedDictionary
was already taken, but SortedList
wasn't. I might have called it SortedListDictionary
or SortedDictionaryList
, but I didn't get to name it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With