集合是否有可能变得碎片化?
考虑在Dictionary
中注册新成员的进入以及进入的时间:
Dictionary<string, DateTime> members = new Dictionary<string, DateTime>();
members.Add("Bob", DateTimeNow);
Thread.Sleep(1000);
members.Add("Joe", DateTimeNow);
Thread.Sleep(1000);
members.Add("Susan", DateTimeNow);
Thread.Sleep(1000);
// Now Joe exits
members.Remove("Joe");
// Then Mike enters
members.Add("Mike", DateTimeNow);
现在的问题是Mike
在Dictionary
中的位置。他是添加到 Dictionary
的末尾还是会填充 Susan
的空位置(如果我们使用 foreach
进行迭代或访问 字典
通过索引)?该行为是否始终得到保证?
Consider registering entrance of new members in a Dictionary
and the time of entrance:
Dictionary<string, DateTime> members = new Dictionary<string, DateTime>();
members.Add("Bob", DateTimeNow);
Thread.Sleep(1000);
members.Add("Joe", DateTimeNow);
Thread.Sleep(1000);
members.Add("Susan", DateTimeNow);
Thread.Sleep(1000);
// Now Joe exits
members.Remove("Joe");
// Then Mike enters
members.Add("Mike", DateTimeNow);
Now the question is where's Mike
location in Dictionary
. Is he added to the end of Dictionary
or he will fill the empty location of Susan
(if we iterate with foreach
or access the Dictionary
via index)? Is the behavior guaranteed for all of the times?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字典没有排序,因此如果您迭代键,您无法对它们返回的顺序进行任何推理。
正如 MSDN 网站告诉我们的,字典是作为哈希表实现的,并且:
如果您想迭代 a 中的键,则应该使用 SortedDictionary定义的顺序。
A Dictionary is not ordered, so you can't do any reasoning as to the order they're returned in if you iterate over the keys.
As the MSDN site tells us, Dictionary is implemented as a hash table, and:
You should use a SortedDictionary if you want to iterate over the keys in a defined order.
Dictionary 所代表的哈希表没有定义顺序的概念。您永远不能依赖特定顺序的项目。无法保证此行为。字典用于通过键快速访问给定的项目。
引自文档:
The notion of order is not defined for hashtable which what Dictionary represents. You can never rely on items being in a particular order. This behavior is not guaranteed. A Dictionary is used to quickly access a given item by key.
Quote from the documentation:
访问
字典
是通过key
完成的,而不是通过index
完成的 - 所以它本身的问题意义不大。正如所有答案已经说明的那样 -
Dictionary
没有顺序,并且通过Hashtable
实现(Wiki 页面 - 花时间阅读它)字典
本身可以扩展并且压缩取决于它维护的数据量和它自己的实现,但是当使用.NET
这样的丰富框架时,你不需要不用管这个问题,它已经为你完成了。如果您感兴趣,可以阅读 WIKI 页面中的动态调整大小
部分来了解其实现。Accessing a
Dictionary
is done viakey
and not viaindex
- so the question it self is meaning less.As all answers already stated - a
Dictionary
has no order, and is implemented via aHashtable
(Wiki Page - Take the time to read it)The
Dictionary
it self can expand and compress depending on the volume of data it maintains and its own implementation, but when using a rich framework like.NET
your don't need to bother with that question, it is done for you. You can read theDynamic Resizing
section in the WIKI page to learn on the implementation if it interests you.