如何访问添加到 HashSet 的最后一个对象?
我有一个 HashSet,它是客户端套接字的集合。当客户端连接时,套接字将被添加到 HashSet 中。然后我需要访问该套接字,但我不知道如何在 HashSet 中访问它。
...
clientSockets.Add(listenerSocket.EndAccept(async));
WaitForData(lastAddedSocket);
....
我如何确定 lastAddedSocket
是什么?
I have a HashSet that is a collection of client sockets. When a client connects, the socket is added to the HashSet. I then need to access that socket, but I don't know how to access it in the HashSet.
...
clientSockets.Add(listenerSocket.EndAccept(async));
WaitForData(lastAddedSocket);
....
How could I determine what lastAddedSocket
is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无法询问 HashSet“最后添加到你身上的东西是什么?”顺序全乱了。
您应该简单地保留一个名为
lastAddedSocket
的单独变量。每次向 HashSet 添加套接字时,也将其分配给lastAddedSocket
。然后你就可以在固定的时间内轻松地查找它。There is no way to ask a HashSet "what was the last thing that was added to you?" The order is all jumbled up.
You should simply keep a separate variable called
lastAddedSocket
. Every time you add a socket to the HashSet, also assign it tolastAddedSocket
. Then you will be able to look it up easily and in constant time.人们普遍认为哈希集的顺序是无法保证的。虽然 Java 文档直接指出了这一点,但 MSDN 给出的最接近的是
信息感谢: HashSet 是否保留插入顺序?
也就是说,它您自己保留最后一个套接字应该相当容易。
It is generally understood that a hashset's order is not guaranteed. While the Java documentation comes right out and says this the closest the MSDN comes is
Information thanks to: Does HashSet preserve insertion order?
That said, it should be fairly easy for you to preserve your last socket yourself.
当您删除最后一个时,您可能希望最后一个是上一个-最后一个。我建议使用 Queue<>除了 HashSet 之外,您还可以始终记住它们到达的顺序,以防最后一个消失。
You will probably want your last to be previous-last when you delete the last one. I recommend using Queue<> in addition to the HashSet so you will be able always remember the sequence in which they arrived, in case that last goes away.